区分大小写的链接在 Chrome 上不起作用。如果 anchor 名称是 link#Anchor1 将不起作用,而 link#anchor1 将起作用。
我继续寻找解决方案并找到了 .toLowerCase() 函数。 现在我有一个无法修复的新问题:Uncaught TypeError:anchorEl.offset is not a function
$(window).load(function()
{
var hashVal= window.location.hash.substring(1).toLowerCase();
var anchorEl = $("a[name='"+hashVal+"']").toLocaleString().toLowerCase().split(',');
var elOffset = anchorEl.offset();
var offsetTop = elOffset.top;
$(document).scrollTop( offsetTop - 200);
console.log(offsetTop);
});
它在 Firefox 上部分有效,除了偏移值,+200 或 -200 不会产生任何影响(它位于导航栏后面),但在 Chrome 上它不会移动一英寸。
最佳答案
尝试如下所示。首先选择所有具有 name
属性的 a
元素,然后选择 filer 与 windows 哈希进行比较。
var anchorEl = $("a[name]").toArray().filter(function(a) {
return $(a).attr('name').toLowerCase() == hashVal.toLowerCase();
});
var elOffset = $(anchorEl).offset();
查看下面的代码。滚动到 300px;
$(window).load(function() {
var hashVal = "Action"; //window.location.hash.substring(1).toLowerCase();
var anchorEl = $("a[name]").toArray().filter(function(a) {
return $(a).attr('name').toLowerCase() == hashVal.toLowerCase();
});
if (anchorEl.length > 0) {
var elOffset = $(anchorEl).offset();
var offsetTop = elOffset.top;
$(document).scrollTop(offsetTop - 200);
console.log(offsetTop);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div style="margin-top: 300px;">
<a href="#" name="action"> action </a>
</div>
<div style="margin-bottom: 300px;">
<a href="#" name="action2"> action2 </a>
</div>
关于javascript - Chrome 上区分大小写的 anchor 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54073197/