我已经阅读了很多关于这个问题的文章,但它们似乎并没有解决我的问题。基本上,在 Firefox 上,子元素(svg)覆盖按钮并阻止它被点击。此代码在 Chrome 中运行良好,但在 Firefox 中运行不正常。我已尝试应用 height: 100%
和 width: 100%
,建议修复此问题,但可点击区域从元素的中途开始(见图)。
如何以跨现代浏览器的方式更正此问题?
我只希望按钮的大小与子元素的大小相同。复杂性来自需要在容器 div 中垂直居中的按钮,这就是它具有 top: 50%
的原因。这是一个可重用的组件,所以我需要一种方法让它以动态的方式垂直居中,所以不能只是修改位置。
我在这里模拟了一个例子:
$('button').on('click', (e) => {
alert('clicked');
});
button {
z-index: 1;
position: absolute;
top: 50%;
background-color: transparent;
border: none;
}
div {
position: absolute;
top: -43px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>
<div>
<svg width="400" height="110">
<rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
Sorry, your browser does not support inline SVG.
</svg>
</div>
</button>
如有任何帮助,我们将不胜感激。
最佳答案
问题不是按钮的绝对位置,而是按钮内 div 的绝对位置。该按钮失去了其中 div 的宽度和高度,就像一个空按钮(宽度和高度 = 0)。
删除您的 div 的绝对位置并使用 calc 将 -43px
添加到您按钮的 top
。
$('button').on('click', (e) => {
alert('clicked');
});
button {
z-index: 1;
position: absolute;
top: calc(50% - 43px);
background-color: transparent;
border: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>
<div>
<svg width="400" height="110">
<rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
Sorry, your browser does not support inline SVG.
</svg>
</div>
</button>
关于html - Firefox 绝对位置防止按钮点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54107330/