如何使用JavaScript添加幻灯片广告位和弹出框功能,下面我将提供完整的代码示例,包括幻灯片广告位和弹出框功能的实现。
一、增加6张幻灯片(首页banner)
<script> document.addEventListener("DOMContentLoaded", function() { function isHomePage() { const path = window.location.pathname; return path === '/' || path.match(/^\/(us|zhcn)\/?$/i); } if (!isHomePage()) return; function detectLanguage() { const langElement = document.querySelector('strong.langx'); if (!langElement) return 'en'; const text = langElement.textContent.trim(); if (text === '中文版') return 'zh'; if (text === 'English') return 'en'; return 'en'; } const langImages = { en: [ { url: "https://file-sg.gname.net/wzpic/20250813/091018689be5fadb98cmH8wib.jpg", link: "/tld-eu-cc.html", title: "Free Domain", alt: "Free Domain" }, { url: "https://file-sg.gname.net/f/imgs/index/20250120/us_index_banner.png", link: "/coupons", title: "Super Coupons", alt: "Super Coupons" }, { url: "https://file-sg.gname.net/f/imgs/index/20250430/ssl_us.png", link: "/batch/ssl", title: "SSL Certificate", alt: "SSL Certificate" }, { url: "https://file-sg.gname.net/f/imgs/index/20250526/vps_us.png", link: "/cps/gcs_buy", title: "Cloud Server", alt: "Cloud Server" }, { url: "https://file-sg.gname.net/f/imgs/index/biaoti_jxsus.png", link: "/agent?ttsrc=reg_banner", title: "Become a Reseller", alt: "Become a Reseller" }, { url: "https://file-sg.gname.net/f/imgs/index/waf_us.png", link: "/cps/waf", title: "Website Protection", alt: "Website Protection" } ], zh: [ { url: "https://file-sg.gname.net/wzpic/20250813/090942689be5d61950aEsUY2Y.jpg", link: "/tld-eu-cc.html", title: "免费域名", alt: "免费域名" }, { url: "https://file-sg.gname.net/f/imgs/index/20250120/zhcn_index_banner.png", link: "/coupons", title: "超值优惠券", alt: "超值优惠券" }, { url: "https://file-sg.gname.net/f/imgs/index/20250430/ssl_zhcn.png", link: "/batch/ssl", title: "SSL证书申请", alt: "SSL证书申请" }, { url: "https://file-sg.gname.net/f/imgs/index/20250526/vps_zhcn.png", link: "/cps/gcs_buy", title: "云服务器购买", alt: "云服务器购买" }, { url: "https://file-sg.gname.net/f/imgs/index/biaoti_jxs.png", link: "/agent?ttsrc=reg_banner", title: "升级经销商", alt: "升级经销商" }, { url: "https://file-sg.gname.net/f/imgs/index/waf_zhcn.png", link: "/cps/waf", title: "网站防护", alt: "网站防护" } ] }; function generateSliderHtml(images) { const style = ` <style> .my-slider-wrapper { width: 100vw; margin-left: calc(-50vw + 50%); background: url("https://file-sg.gname.net/f/imgs/huigou_banner.png") no-repeat; margin-bottom: 10px; margin-top: -14px; padding: 10px 0 20px 0; overflow: hidden; background-size: cover; } .my-slider-container { max-width: 1200px; height: 300px; margin: 0 auto; overflow: hidden; position: relative; box-shadow: 0 2px 5px rgba(0,0,0,0.1); border-radius: 8px; } .my-slider { display: flex; width: ${images.length * 100}%; height: 100%; transition: transform 0.5s ease; } .my-slide { width: ${100/images.length}%; height: 100%; flex-shrink: 0; } .my-slide a { display: block; width: 100%; height: 100%; } .my-slide img { width: 100%; height: 100%; object-fit: contain; padding: 0 10px; box-sizing: border-box; } .my-slider-nav { position: absolute; bottom: 15px; left: 50%; transform: translateX(-50%); display: flex; gap: 8px; z-index: 10; } .my-slider-nav button { width: 10px; height: 10px; border-radius: 50%; border: none; background-color: rgba(255, 255, 255, 0.5); cursor: pointer; transition: all 0.3s; padding: 0; } .my-slider-nav button.active { background-color: #fff; transform: scale(1.2); } .my-slider-btn { position: absolute; top: 50%; transform: translateY(-50%); width: 36px; height: 36px; background-color: rgba(255, 255, 255, 0.3); color: #333; border: none; border-radius: 50%; font-size: 18px; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all 0.3s; z-index: 10; backdrop-filter: blur(2px); } .my-slider-btn:hover { background-color: rgba(255, 255, 255, 0.8); } .my-slider-btn.prev { left: 15px; } .my-slider-btn.next { right: 15px; } @media (max-width: 768px) { .my-slider-container { height: 200px; } .my-slider-btn { width: 30px; height: 30px; font-size: 16px; } } </style> `; let slidesHtml = ''; let navButtonsHtml = ''; images.forEach((img, index) => { slidesHtml += ` <div class="my-slide"> <a href="${img.link}" title="${img.title}" target="_blank"> <img src="${img.url}" alt="${img.alt}" loading="lazy"> </a> </div>`; navButtonsHtml += `<button class="${index === 0 ? 'active' : ''}"></button>`; }); return `${style} <div class="my-slider-wrapper"> <div class="my-slider-container"> <div class="my-slider">${slidesHtml}</div> <button class="my-slider-btn prev">❮</button> <button class="my-slider-btn next">❯</button> <div class="my-slider-nav">${navButtonsHtml}</div> </div> </div>`; } function initSlider() { const currentLang = detectLanguage(); const bannerHtml = generateSliderHtml(langImages[currentLang]); const container = document.querySelector(".swiper-container") || document.body; container.insertAdjacentHTML('beforebegin', bannerHtml); const slider = document.querySelector('.my-slider'); const slides = document.querySelectorAll('.my-slide'); const prevBtn = document.querySelector('.my-slider-btn.prev'); const nextBtn = document.querySelector('.my-slider-btn.next'); const navButtons = document.querySelectorAll('.my-slider-nav button'); let currentIndex = 0; const slideCount = slides.length; function updateSlider() { slider.style.transform = `translateX(-${currentIndex * (100/slideCount)}%)`; navButtons.forEach((btn, index) => { btn.classList.toggle('active', index === currentIndex); }); } nextBtn.addEventListener('click', () => { currentIndex = (currentIndex + 1) % slideCount; updateSlider(); }); prevBtn.addEventListener('click', () => { currentIndex = (currentIndex - 1 + slideCount) % slideCount; updateSlider(); }); navButtons.forEach((button, index) => { button.addEventListener('click', () => { currentIndex = index; updateSlider(); }); }); let interval = setInterval(() => { currentIndex = (currentIndex + 1) % slideCount; updateSlider(); }, 5000); const sliderContainer = document.querySelector('.my-slider-container'); sliderContainer.addEventListener('mouseenter', () => clearInterval(interval)); sliderContainer.addEventListener('mouseleave', () => { interval = setInterval(() => { currentIndex = (currentIndex + 1) % slideCount; updateSlider(); }, 5000); }); // 触摸设备支持 let touchStartX = 0; let touchEndX = 0; sliderContainer.addEventListener('touchstart', (e) => { touchStartX = e.changedTouches[0].screenX; }, {passive: true}); sliderContainer.addEventListener('touchend', (e) => { touchEndX = e.changedTouches[0].screenX; handleSwipe(); }, {passive: true}); function handleSwipe() { const threshold = 50; if (touchEndX < touchStartX - threshold) { // 向左滑动,下一张 currentIndex = (currentIndex + 1) % slideCount; } else if (touchEndX > touchStartX + threshold) { // 向右滑动,上一张 currentIndex = (currentIndex - 1 + slideCount) % slideCount; } updateSlider(); } } initSlider(); // 优化语言切换监听 const langElement = document.querySelector('strong.langx'); if (langElement) { const observer = new MutationObserver(() => { const existingSlider = document.querySelector('.my-slider-wrapper'); if (existingSlider) { existingSlider.remove(); initSlider(); } }); observer.observe(langElement, { characterData: true, childList: true, subtree: true }); } }); </script>
二、在某个链接后面注入新的内容
<script> document.addEventListener("DOMContentLoaded", function() { // **1. 改进语言检测逻辑** function detectLanguage() { // 检查所有 .langx 元素,看是否有 "English" 或 "中文版" const langElements = document.querySelectorAll('.langx'); for (const el of langElements) { const text = el.textContent.trim(); if (text === 'English') return 'english'; if (text === '中文版') return 'chinese'; } // 默认返回中文(可根据需求调整) return 'chinese'; } const currentLang = detectLanguage(); const isEnglish = currentLang === 'english'; // **2. 动态生成页脚链接(优化重复逻辑)** const footerLinks = [ { selector: ".foot_list.fw_zc", enHtml: ` <dd> <a href="/agent?ttsrc=foot_nav" title="Become an Agent" style="color:#f2f2f2;"> <img src="https://file-sg.gname.net/uploads/20250811/1732296899b8adc996cdK6Rdj.png?t=20250811161500" width="20px" height="20px" style="float:left; margin:3px 8px 0 0;" /> <b style="color:#f2f2f2;">Join Us!</b> as an agent</a> </dd> `, zhHtml: ` <dd> <a href="/agent?ttsrc=foot_nav" title="成为代理商" style="color:#f2f2f2;"> <img src="https://file-sg.gname.net/uploads/20250811/1732296899b8adc996cdK6Rdj.png?t=20250811161500" width="20px" height="20px" style="float:left; margin:3px 8px 0 0;" /> <b style="color:#f2f2f2;">加入我们</b>,成为经销商 </a> </dd> ` }, { selector: ".foot_list:nth-of-type(1)", enHtml: '<dd><a href="/user#/wt_add">Submit work order</a></dd>', zhHtml: '<dd><a href="/user#/wt_add">提交工单</a></dd>' } ]; // **3. 插入HTML,避免重复插入** footerLinks.forEach(link => { const element = document.querySelector(link.selector); if (element) { // 检查是否已经插入过(防止重复执行) const existingLink = element.querySelector(`a[href="${isEnglish ? '/agent?ttsrc=foot_nav' : '/abuse'}"]`); if (!existingLink) { element.insertAdjacentHTML('beforeend', isEnglish ? link.enHtml : link.zhHtml); } } }); }); </script>
三、底部悬浮广告位,点击关闭后10分钟内不再显示
<div class="footShow footShow15" style="bottom: 40px;"> <img id="languageAdImg" src="" alt=""> <a href="/coupons" target="_self" style="height: 36px;right: 100px;width: 120px;top: 39px;"></a> <i class="footShow-close footShow-close15"></i> </div> <script> // 根据语言设置广告图片 function setAdImageByLanguage() { const langElements = document.querySelectorAll('.langx'); let currentLang = '中文版'; // 默认语言 // 检测当前选中的语言 langElements.forEach(el => { if (el.classList.contains('active') || el.style.display !== 'none') { currentLang = el.textContent.trim(); } }); // 根据语言设置图片URL const adImg = document.getElementById('languageAdImg'); if (currentLang === 'English') { adImg.src = "https://file-sg.gname.net/f/imgs/index/20250707/us_index_tc.png"; } else { adImg.src = "https://file-sg.gname.net/f/imgs/index/20250707/zhcn_index_tc.png"; } } // 页面加载时设置图片 document.addEventListener('DOMContentLoaded', setAdImageByLanguage); // 如果语言切换是动态的(例如通过点击),需要监听语言切换事件 // 假设语言切换是通过点击 .langx 元素实现的,可以添加以下代码: document.querySelectorAll('.langx').forEach(el => { el.addEventListener('click', function() { // 这里可能需要根据你的实际语言切换逻辑调整 // 例如,移除其他语言的 active 类,给当前点击的语言添加 active 类 document.querySelectorAll('.langx').forEach(langEl => { langEl.classList.remove('active'); }); this.classList.add('active'); // 切换语言后更新广告图片 setAdImageByLanguage(); }); }); function gnPopUp(el, el1) { // 检查是否在10分钟关闭期内 const closeTime = localStorage.getItem('adCloseTime'); if (closeTime) { const now = new Date().getTime(); const tenMinutes = 10 * 60 * 1000; // 10分钟毫秒数 if (now - closeTime < tenMinutes) { $(el).hide(); // 在关闭期内,不显示弹窗 return; } } // 显示弹窗 $(el).show(); $(el).stop(true, true).animate({ bottom: "40px" }, 800); $(el1).click(function () { // 记录关闭时间 localStorage.setItem('adCloseTime', new Date().getTime()); // 关闭动画 $(el).stop(true, true).animate({ bottom: "-100%" }, 800); setTimeout(function() { $(el).hide(); }, 500); }); } // 弹窗内容显示 gnPopUp('.footShow15', '.footShow-close15'); var swiper_index = 0; var swiper = new Swiper('.banner-swiper', { direction: 'vertical', // 垂直切换选项 speed: 800, autoplay: { delay: 5000, disableOnInteraction: false }, noSwiping: true, noSwipingClass: 'stop-swiping', loop: true, effect: 'fade', fadeEffect: { crossFade: true, }, pagination: { el: '.swiper-pagination', type: 'custom', clickable: true, renderCustom: function (swiper, current, total) { swiper_index = current; var paginationHtml = ""; for (var i = 0; i < total; i++) { if (i === (current - 1)) { paginationHtml += '<span class="swiper-pagination-customs swiper-pagination-customs-activ"><div class="straight"></div></span>'; } else { paginationHtml += '<span class="swiper-pagination-customs"><div class="straight"></div></span>'; } } return paginationHtml; }, } }); </script>
四、网页弹出公告(关闭后10分钟内不再)
<script> document.addEventListener('DOMContentLoaded', function() { // 检查是否在10分钟内已经关闭过弹窗 const lastClosedTime = localStorage.getItem('popupClosedTime'); if (lastClosedTime && (Date.now() - parseInt(lastClosedTime) < 600000)) { return; // 10分钟内不重复弹出 } // 判断当前语言版本 const langElement = document.querySelector('strong.langx'); const isChinese = langElement && langElement.textContent.includes('中文版'); const isEnglish = langElement && langElement.textContent.includes('English'); // 创建弹窗容器 const popup = document.createElement('div'); popup.id = 'debug-popup'; popup.style.cssText = ` position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 90%; max-width: 500px; background-color: #fff; border-radius: 6px; box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2); z-index: 1000; display: none; overflow: hidden; font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif; `; // 弹窗头部(标题 + 关闭按钮) const popupHeader = document.createElement('div'); popupHeader.style.cssText = ` position: relative; padding: 8px 20px; background-color: #3273dc; color: white; `; // 标题 const popupTitle = document.createElement('h3'); popupTitle.textContent = isChinese ? '关于免费注册.eu.cc后缀活动上线公告' : 'Free .eu.cc Domain Registration Now Available'; popupTitle.style.cssText = ` margin: 0; font-size: 18px; font-weight: 600; `; // 关闭按钮(右上角) const closeButton = document.createElement('button'); closeButton.innerHTML = '×'; closeButton.style.cssText = ` position: absolute; top: 50%; right: 15px; transform: translateY(-50%); background: none; border: none; color: white; font-size: 24px; cursor: pointer; padding: 0 8px; transition: opacity 0.2s; `; closeButton.onmouseover = () => closeButton.style.opacity = '0.7'; closeButton.onmouseout = () => closeButton.style.opacity = '1'; // 弹窗内容区域(根据语言动态设置) const popupContent = document.createElement('div'); popupContent.innerHTML = isChinese ? ` <p style="margin: 0; padding:10px 20px;font-size: 16px; color: #666;text-indent:2em;"> 所有本站注册用户均可参与免费注册.eu.cc后缀域名活动,免费注册.eu.cc后缀是以领取全额抵扣券的形式发放到账户中。优惠券领取成功后有效期为30天,逾期作废,不退不换。请注意使用时间,优惠券不支持转赠,仅限用户对应账户使用。<a href="/tld-eu-cc.html" title="免费注册.eu.cc后缀域名" style="font-weight:bold;color:red;font-size: 16px;">点击立即注册</a> </p> <p style="text-align:right;margin-right:50px;font-size: 14px; padding:10px 20px;">JIANNAME.COM<br />2025年8月13日</p> ` : ` <p style="margin: 0; padding:10px 20px;font-size: 16px; color: #666;text-indent:2em;"> All registered users of our website can participate in the free registration of .eu.cc domain suffix. The free .eu.cc registration is issued in the form of a full coupon to your account. The coupon is valid for 30 days after claiming and will expire if not used. Please note the usage time; the coupon is non-transferable and can only be used by the corresponding user account. <a href="/tld-eu-cc.html" title="Free .eu.cc domain registration" style="font-weight:bold;color:red;font-size: 16px;">Click to register now</a> </p> <p style="text-align:right;margin-right:50px;font-size: 14px; padding:10px 20px;">JIANNAME.COM<br />August 13, 2025</p> `; // 组装弹窗 popupHeader.appendChild(popupTitle); popupHeader.appendChild(closeButton); popup.appendChild(popupHeader); popup.appendChild(popupContent); document.body.appendChild(popup); // 添加动画 const style = document.createElement('style'); style.textContent = ` @keyframes popupFadeIn { from { opacity: 0; transform: translate(-50%, -50%) scale(0.95); } to { opacity: 1; transform: translate(-50%, -50%) scale(1); } } #debug-popup { animation: popupFadeIn 0.3s ease-out; } `; document.head.appendChild(style); // 显示弹窗 setTimeout(() => popup.style.display = 'block', 300); // 点击关闭按钮 closeButton.addEventListener('click', function() { // 记录关闭时间(10分钟内不再显示) localStorage.setItem('popupClosedTime', Date.now().toString()); // 关闭动画 popup.style.animation = 'none'; popup.style.transition = 'opacity 0.2s'; popup.style.opacity = '0'; setTimeout(() => document.body.removeChild(popup), 200); }); // 10分钟后自动清除记录(可选) setTimeout(() => { localStorage.removeItem('popupClosedTime'); }, 600000); }); </script> <style> /* 重写部分样式 */ .header_nav { background:#110d31 !important} .nav_ul .nav_li a{color: #aab3c9;} .nav_ul .nav_li .nav_icon, .login, .nav_r2 .userid{color: #a5afc7;} .header_sec span, .sec_down li {color: #abb1c1;} .header_sec {border-radius: 3px; border: 1px solid rgba(255, 255, 255, 0.5);} .header_sec span, .sec_down li {color: #b5bfd7;} .login {border: 0px solid rgb(239 232 232 / 30%);} .register {background: #1d2c63;} .btn:hover {background: linear-gradient(180deg, rgb(26 53 107) 0%, rgb(18 47 105) 64%, rgb(16 27 61) 100%) !important; cursor: pointer !important;} .index_notice {background: #fff;} .ymreg_bottom_box {display:none;} .header_sec strong{color:#cdcdcd;} .header_sec span, .sec_down li {color: #14203e;} .header_sec span i{color:#cdcdcd;} </style>
版权声明:本文除非特别标注,否则均为本站原创文章,转载或引用请注明来源及作者,并保留本文原始链接!
还木有评论哦,快来抢沙发吧~