2016-08-02 164 views
0
$('.mainNav a[href^="#"]').on('click', function (event) { 
    var target = $(this.getAttribute('href')); 
    if (target.length) { 
    event.preventDefault(); 
    $('body').stop(true).animate({ 
     scrollTop: target.offset().top - 130 
    }, 1000); 
    } 
    return false; 
}); 

我尝试使用preventDefault()但仍闪烁闪烁使用动画和滚动到

+0

闪烁究竟是什么? –

回答

0

这里的时候是我会做什么:
- 你不需要因为你使用preventDefault()返回false,你应该把它任何条件语句
之前 - 你不需要truestop()功能
- 你应该使用$('html, body')代替$('body')

$('.mainNav a[href^="#"]').on('click', function (event) { 
    var target = $($(this).attr('href')); 
    event.preventDefault(); 
    if (target.length){ 
     $('html, body').stop().animate({ 
      scrollTop: target.offset().top - 130 
     }, 1000); 
    } 
}); 

但是,如果它不能解决您的问题,也许做一个jsfiddle或codepen向我们展示?因为闪烁可能是由于脚本本身以外的其他元素引起的。

0

hmm。在这里没有看到你的问题。除了一些小问题与你的JQ码

做了一个简单的例子。看到这里jsfiddle

或代码片段如下:

$('.mainNav a[href^="#"]').on('click', function (event) { 
 
    event.preventDefault(); 
 
    var target = $(this.getAttribute('href')); 
 
    if (target.length) { 
 
    $('html,body').stop().animate({ 
 
     scrollTop: target.offset().top - 130 
 
    }, 1000); 
 
    } 
 

 
});
h1 { 
 
    color:#fff; 
 
    font-size:30px; 
 
    margin:0 
 
} 
 
#home { 
 
    height:300px; 
 
    background:red; 
 
    margin-top:48px; 
 
} 
 
#about { 
 
    height:600px; 
 
    background:green 
 
} 
 
#contact { 
 
    height:200px; 
 
    background:blue; 
 
} 
 
ul li { 
 
    list-style:none; 
 
    display:inline-block 
 
} 
 
ul { 
 
    position:fixed; 
 
    padding:15px 0; 
 
    width:100%; 
 
    background:rgba(255,255,255,0.6); 
 
    top:0; 
 
    margin:0 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul class="mainNav"> 
 
<li><a href="#home">Home</a></li> 
 
<li><a href="#about">About</a></li> 
 
<li><a href="#contact">Contact</a></li> 
 
</ul> 
 
<div id="home"> 
 
<h1>WELCOME !</h1> 
 
</div> 
 
<div id="about"> 
 
<h1>About Us</h1> 
 
</div> 
 
<div id="contact"> 
 
<h1>Contact Us</h1> 
 
</div>

+0

非常感谢..它的工作... –