所以我写了一些 Javascript,当用户点击按钮时滚动到文档中的某个位置:
document.getElementById("navContact").addEventListener("click", scrollToSection);
function scrollToSection() {
/* this = element on which the user clicked */
smoothScroll(this.attributes[0].value.split("#")[1]);
}
它很好、简单、易于阅读和调试。唯一的问题是它通过从命名节点映射中读取它来获取它必须滚动到的部分的名称。在我的标记中,属性的顺序如下:
<a href="#contact_us" id="navContact"></a>
<--! document.getElementById("navContact").attributes = [href="contact_us", id="navContact"] -->
但是当我在 Edge 的 DOM 资源管理器中检查它时,属性被重新排序:
<a id="navContact" href="#contact_us"></a>
<--! document.getElementById("navContact").attributes = [id="navContact", href="contact_us"] -->
根据 Josiah Keller 的建议,我将 js 更改为使用 element.getAttribute()
而不是 this.attributes
。
与此同时,我很想知道 Edge 为什么要这样做?
最佳答案
.attributes
返回一个 NamedNodeMap。 According to MDN :
The NamedNodeMap interface represents a collection of Attr objects. Objects inside a NamedNodeMap are not in any particular order, unlike NodeList, although they may be accessed by an index as in an array.
虽然您可以使用 this.attributes[0]
引用它,但您会注意到您不能 push
它,因为它不是数组。它是一个对象,它是在没有考虑顺序的情况下构建的,因此它可能不是 Edge 中的错误。它仍在返回它应该返回的内容,即无序对象。
正如其他人所建议的那样,您应该专门获取 href,但希望这能说明为什么它没有像您想象的那样工作。
关于javascript - 为什么 Microsoft Edge 在呈现页面之前重新排序 html 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45002558/