此函数使用动画从导航滚动到#id,并为其着色 bg-color 颜色几秒钟。
这是我用来从导航向下滚动到页面上使用的内容的功能,方法是使用它 id <h1 id="#someid">
和 href="#someid"
anchor 标签中的属性。该功能工作正常,但是,它在加载页面后第一次点击时不起作用。知道如何解决它以及是什么原因造成的吗?
//EXTERNAL JAVASCRIPT
function link(){
$('a[href^="#"]').click(function() {
var target = $(this.hash);
if (target.length == 0) target = $('a[name="' + this.hash.substr(1) + '"]');
if (target.length == 0) target = $('html');
$('html, body').animate({ scrollTop: target.offset().top }, 100);
target[0].style.backgroundColor = 'red';
setTimeout(function(){
target[0].style.backgroundColor = 'dodgerBlue';
}, 8000);
return false;
});
}
这是我的 HTML,我只是通过将 anchor onclick 属性链接到我的函数的 link();
来覆盖它。您可以在本文上方看到。
//HTML
<li class="sub-menu-element"><a href="#DERMATOLOG" onclick="javascript:link()">DERMATOLOG</a></li>
有什么想法吗? 非常感谢您提前提供帮助。
最佳答案
您正在从内联 javascript 调用 link()
函数,并再次调用 link()
函数内的点击事件。这是没有意义的,根本不需要......
试试这个
$(function(){ //call the codes after this when document is ready...
$('a[href^="#"]').click(function() { //call the click event
var target = $(this.hash);
if (target.length == 0) target = $('a[name="' + this.hash.substr(1) + '"]');
if (target.length == 0) target = $('html');
$('html, body').animate({ scrollTop: target.offset().top }, 100);
target[0].style.backgroundColor = 'red';
setTimeout(function(){
target[0].style.backgroundColor = 'dodgerBlue';
}, 8000);
return false;
});
});
有了这个..你也不需要内联的onclick
<li class="sub-menu-element"><a href="#DERMATOLOG">DERMATOLOG</a></li>
关于javascript - onclick 函数不运行第一次点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15464499/