点击不同导航链接切换Div内容并实现交叉淡入淡出的方法
单页网站交叉淡入淡出内容切换解决方案
关于this作用域的问题
你的判断完全正确:在HTML的onclick属性中直接调用函数时,this默认指向全局window对象,而非触发点击的<a>元素,所以$(this).attr("href")会返回undefined。
快速修复this指向的方法
在调用函数时手动传递当前元素:
<a href="#about" class="w3-bar-item w3-hide-small" style="width:16.5%" onclick="showContent(this)">About</a>
对应的函数修改为:
function showContent(el) { var hrefValue = $(el).attr("href"); alert(hrefValue); // 现在能正确获取#about }
实现交叉淡入淡出的完整方案
直接切换W3CSS的w3-show/w3-hide类是瞬间显示/隐藏,没有过渡效果。推荐结合jQuery的动画方法实现平滑交叉过渡,完整代码示例如下:
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- 导航栏 --> <div class="w3-bar"> <a href="#home" class="w3-bar-item w3-hide-small nav-link" style="width:16.5%">Home</a> <a href="#about" class="w3-bar-item w3-hide-small nav-link" style="width:16.5%">About</a> </div> <!-- 内容区域 --> <div id="home" class="w3-container w3-green content-section" style="height:50px; display:block"></div> <div id="about" class="w3-container w3-red content-section" style="height:50px; display:none"></div> <script> $(function() { // 给所有导航链接绑定点击事件 $(".nav-link").on("click", function(e) { e.preventDefault(); // 阻止锚点跳转导致的页面滚动 var targetId = $(this).attr("href"); var $activeSection = $(".content-section:visible"); var $targetSection = $(targetId); // 交叉淡入淡出:旧内容淡出后,新内容淡入 $activeSection.fadeOut(300, function() { $targetSection.fadeIn(300); }); // 可选:给当前激活的导航链接添加高亮样式 $(".nav-link").removeClass("w3-blue"); $(this).addClass("w3-blue"); }); }); </script>
方案说明
- 用
fadeOut()和fadeIn()实现平滑过渡,参数300是动画时长(单位:毫秒),可根据需求调整 - 使用jQuery事件绑定代替HTML内联
onclick,代码更整洁易维护 - 调用
e.preventDefault()避免锚点跳转导致的页面滚动 - 可选的导航高亮样式,能提升用户对当前页面的感知
替代方案(结合W3CSS过渡)
如果想继续使用W3CSS的类,可以给内容区域添加过渡样式,实现平滑切换:
.content-section { transition: opacity 0.3s ease; }
对应的JS代码修改为:
$activeSection.addClass("w3-opacity-0").removeClass("w3-show"); setTimeout(function() { $activeSection.addClass("w3-hide"); $targetSection.removeClass("w3-hide").addClass("w3-show").removeClass("w3-opacity-0"); }, 300);
需要提前定义w3-opacity-0类(或直接设置opacity: 0)。
内容的提问来源于stack exchange,提问作者timothys_monster
相关产品推荐
相关产品推荐

