显示覆盖 DIV 时不需要的浏览器滚动条更改

Unwanted browser scrollbar change when overlaying DIV is displayed

本文关键字:浏览器 滚动条 不需要 覆盖 DIV 显示      更新时间:2023-09-26

我有一个具有以下样式的 DIV:

#dialog_overlay {
    width:100%;
    height:100%;
    background:#000000;
    opacity: 0.5;
    position:absolute;
    top:0;
    left:0;
    z-index:2000;
    display:none;
}

在我的页面底部有一个链接:

<a href="#" onClick="test()">Test</a>

函数测试如下所示:

function test()
{
var overlay = $('#dialog_overlay')[0];
var body = document.body;
var html = document.documentElement;
var height = Math.max( html.scrollHeight, html.offsetHeight, body.scrollHeight, body.offsetHeight, html.clientHeight );
overlay.style.height = height + "px";
overlay.style.display = 'inline';
}

我想在单击页面底部的链接时保持浏览器滚动条位置不变。现在发生的事情是,当显示 DIV 时,滚动条总是弹出。有谁知道如何将滚动条保持在单击链接之前的位置?

你必须

使用event.preventDefault();

function test(e)
{
    e.preventDefault();
    ...
}