【问题标题】:Firefox absolute position preventing button clickFirefox 绝对位置防止按钮点击
【发布时间】:2019-06-04 01:29:51
【问题描述】:
我已经阅读了很多关于此问题的内容,但它们似乎无法解决我的问题。基本上,在 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>
任何帮助将不胜感激。
【问题讨论】:
标签:
html
css
firefox
cross-browser
【解决方案1】:
问题不是按钮的绝对位置,问题是按钮内 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>
【解决方案2】:
这是因为您已将 position:absolute 分配给所有 div,它占据了窗口的顶部位置,因此事件不会触发。我还计算了垂直对齐,看到它工作here。
HTML:
<button>
<div>
<svg width="400" height="110">
<rect width="100%" 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>
CSS:
button {
z-index: 1;
position: absolute;
top: calc(50% - 55px);
background-color: transparent;
border: none;
cursor: pointer;
}
JS:
$('button').on('click', (e) => {
alert('clicked');
});