你好我正在創建一個頁面網站,所以我需要的,例如,如果section2出現在視口添加類活動鏈接與href =「section2」。
當滾動時將類添加到導航欄項目
例我需要什麼one page website
$(document).ready(function() {
$(".links a").click(function (e) {
if (this.getAttribute("href").charAt(0) == "#") {
e.preventDefault();
$(this).addClass("active").siblings().removeClass("active");
$("html, body").stop();
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top
}, 1400)
}
else {
$($(this)).attr("target", "_blank")
}
})
})
.links{
width:600px;
position:fixed;
top:0;
padding:20px;
}
.links a{
display:inline-block;
padding:10px 20px;
border:1px solid #02e62a;
color:#02e62a;
text-decoration:none;
}
.links a:hover, .links a.active{
color:#fe0101;
border-color:#fe0101;
}
.section{
width:400px;
height:200px;
margin:300px auto 600px;
background-color:#0094ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="links">
<a href="#home">Section 1</a>
<a href="#about">Section 2</a>
<a href="http://google.com" target="_blank">External Link</a>
<a href="#services">Section 3</a>
<a href="#contact">Section 4</a>
</div>
<div id="home" class="section"></div>
<div id="about" class="section"></div>
<div id="services" class="section"></div>
<div id="contact" class="section"></div>
注:請不要推薦我使用任何插件。
旁註:你的外部鏈接錯誤:) – niceman
爲什麼它是錯誤的:) –
當你說「當section2出現在視口」你的意思是什麼時候通過JavaScript動態添加的東西?因爲'section2'是一個div,一個空的div,它已經出現,它的外觀什麼都沒有:) – niceman