簡體   English   中英

使用動畫並滾動到時閃爍

[英]Flickering when using animate and scroll to

$('.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()但仍然閃爍

這是我會做的:
-您不需要返回false,因為您使用了preventDefault() ,應將其放在任何條件語句之前
-您在stop()函數中不需要true
-您應該使用$('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向我們展示嗎? 因為閃爍可能是由於腳本本身之外的其他因素引起的。

嗯。 在這里看不到您的問題。 除了您的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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM