javascript - 更改#anchor 的默认起始位置

标签 javascript jquery html css

我有一个带有 anchor 的 URL,它可以正常工作:

site.com/item/id#comment-233

打开时, anchor 将恰好位于页面顶部。

如何更改起点?假设我希望它从顶部向下 50px

我需要这个的原因是因为我在页面顶部有固定层,所以评论在固定标题 div 后面出现重叠。

为了以防万一,由于跨浏览器的合规性,我更喜欢一种解决方案,它不涉及将评论的容器更改为固定的和定位顶部减去标题的高度。

最佳答案

假设您的 <a>标签没有内容,用 position:relative; top:-50px; 给标签添加一个类

根据您的文档,您也必须将其包装在绝对 <div>

如果正确实现,这应该是跨浏览器兼容的。

编辑

这是我在本地做的测试,在 FF 3.6 中运行良好

<html>

    <body style='margin:0; padding:0;'>
        <div style='position:fixed; height:50px; background-color:#F00; width:100%'>
        Fixed header
        </div>
        <div style='padding-top:50px'>
            <div style='height:100px; margin-top:10px; background-color:#0F0'><a href='#linkhere'>Go to anchor</a></div>
            <div style='height:100px; margin-top:10px; background-color:#0F0'>Blah</div>
            <div style='height:100px; margin-top:10px; background-color:#0F0'>Blah</div>
            <div style='height:100px; margin-top:10px; background-color:#0F0'>
                <a name='linkhere' style='position:relative; top:-75px;'></a>
            Link here</div>
            <div style='height:100px; margin-top:10px; background-color:#0F0'>Blah</div>
            <div style='height:100px; margin-top:10px; background-color:#0F0'>Blah</div>
            <div style='height:100px; margin-top:10px; background-color:#0F0'>Blah</div>
            <div style='height:100px; margin-top:10px; background-color:#0F0'>Blah</div>
            <div style='height:100px; margin-top:10px; background-color:#0F0'>Blah</div>
            <div style='height:100px; margin-top:10px; background-color:#0F0'>Blah</div>
            <div style='height:100px; margin-top:10px; background-color:#0F0'>Blah</div>
            <div style='height:100px; margin-top:10px; background-color:#0F0'>Blah</div>
            <div style='height:100px; margin-top:10px; background-color:#0F0'>Blah</div>
            <div style='height:100px; margin-top:10px; background-color:#0F0'>Blah</div>
            <div style='height:100px; margin-top:10px; background-color:#0F0'>Blah</div>
            <div style='height:100px; margin-top:10px; background-color:#0F0'>Blah</div>
        </div>
    </body>
</html>

关于javascript - 更改#anchor 的默认起始位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4996330/

相关文章:

javascript - 确保组件只能是特定父组件的子组件

javascript - jQuery UI 对话框文本是否有换行选项?

html - 以响应速度的百分比设置元素的宽度

jquery - 使用变换时的堆叠顺序(z-index)

html - 子元素水平溢出时,为什么忽略了父元素的右填充?

Math 对象的 JavaScript 代码

javascript - [Vue 警告] : Property or method "games" is not defined on the instance but referenced during render

javascript - 如何找到unicode组合?

php - Datatables Jquery 无法从表提交 POST

javascript - jquery 从 JSON 数组中的选择框中收集所有选项值