带有onclick事件的绝对定位适用于Chrome,但不适用于Firefox

时间:2018-12-06 18:33:42

标签: javascript html google-chrome firefox

我遇到一个由绝对定位图像设置样式并附加到onclick事件的按钮的问题。此处的代码在chrome中有效,但在Firefox中无效(在chrome中,单击按钮后我可以看到警报,但是在Firefox中,单击无效):

function buttonClick(id) {
  alert("button clicked: " + id)
}
.gameButtons {
    position: absolute;
    margin: auto;
    height: 6vh;
}

#environment {
    overflow: hidden;
    position:absolute; 
    height:100%;
    width:100%;
}
<div id="environment">
  <div id="allGameButtons">
    
    <button id="s1b" onclick="buttonClick(this.id);"><img src="https://akm-img-a-in.tosshub.com/indiatoday/images/story/201708/cats-xl_080817011942.jpg" id="s1" class="gameButtons" style="height: 8vh; left:51vw; top:65vh;" alt="s1_button"></button>
  
  </div>
</div>

在阅读了该问题之后,似乎在firefox中,应用于.gameButtons的position:absolute将图像放置在按钮的前面,使其不可单击。我已经测试了解决方案,包括将z-indexes添加到.gameButtons和#s1b,将.gameButtons位置更改为相对位置(这会错位图像),以及在javascript中而不是在html中添加onclick事件。有什么想法可以找到适用于两种浏览器的解决方案吗?

感谢您的任何建议。

1 个答案:

答案 0 :(得分:0)

更新: 我找到了一种简化html代码的解决方案,因此仅需将定位应用于一个元素,并且它似乎在两种浏览器中都可以工作。我还发现,仅使用一个css类,并为该类中的图像提供更多属性,即可使工作更顺畅:

                                  

function buttonClick(id) {
  alert("button clicked: " + id)
}
.allGameButtons {
    position:absolute;
    width: 100%;
    height:100%;
    z-index: 1001;
}

.allGameButtons img {
    position:absolute;
    height:6vh;
    margin:auto;
}
<div id="environment">
  <div class="allGameButtons">
    <img src="https://openclipart.org/image/2400px/svg_to_png/306882/1537209550.png" style="height: 8vh; left:51vw; top:65vh;" id="s1b" alt="s1_button" onclick="buttonClick(this.id);" />
  </div>
</div>