我正在尝试制作一个简单的“scrollTo element”函数。
控制台向我显示错误: 语法错误,无法识别的表达式:a[href^=#] for a[href^=#] code
根据对 这个问题 的回复,我将哈希符号用双引号引起来,但现在控制台为此显示 Unexpected token ILLEGAL 。
请解释我做错了什么以及如何解决它。
这是我的代码:
$(document).on('click', 'a[href^=#]', function () {
$('html, body').animate({ scrollTop: $('section[data-target="'+this.hash.slice(1)+'"]').offset().top }, 1000 );
return false;
});
menu {
background-color: #1abc9c;
height: 50px;
position: fixed;
left: 0;
top: 0;
width: 100%;
margin: 0;
padding: 0;
}
menu ul li {
display: inline-block;
padding: 0 15px;
}
menu ul li a {
color: #333;
text-decoration: none;
}
section {
height: 300px;
padding: 60px 0 0 45px;
}
.one {
background-color: #3498db;
}
.two {
background-color: #e74c3c;
}
.three {
background-color: #f39c12;
}
.four {
background-color: #2c3e50;
}
<menu>
<ul>
<li><a href="#one">One</a></li>
<li><a href="#two">Two</a></li>
<li><a href="#three">Three</a></li>
<li><a href="#four">Four</a></li>
</ul>
</menu>
<section class="one" data-target="one">Section One</section>
<section class="two" data-target="two">Section Two</section>
<section class="three" data-target="three">Section Three</section>
<section class="four" data-target="four">Section Four</section>
原文由 Alexandr Belov 发布,翻译遵循 CC BY-SA 4.0 许可协议
由于
#
是 jquery 的 元字符,您必须使用 引号 将其包装起来,或者必须使用\\
对其进行转义,要么
演示