按钮在固定位置div内无响应

时间:2020-09-07 19:24:31

标签: javascript html css button position

我使用的是固定在#zoom-controls上的位置,因此在我滚动时button会停留在屏幕顶部。在我将position: fixed添加到div之前,这些按钮起作用了,但是如果我添加position: fixed,则button将变得无响应。

在fiddlejs上使用它后,我发现如果删除svg(这是div的同级按钮),即使div固定,按钮也可以工作。我需要svg留下来。

以下是带有svgposition: fixed的代码-因此无法正常工作:

var butt = document.getElementById('zoom_in');

butt.addEventListener('click', () => {
  var body = document.getElementById('body');
  var p = document.createElement('p');
  p.textContent = 'pressed';
  body.appendChild(p);
});
.draggable {
  cursor: move;
}

.pdf-page-canvas {
  display: block;
  margin: 5px auto;
  border: 1px solid rgba(0, 0, 0, 0.2);
  z-index: 0;
}

.canvas_container {
  width: 100%;
  /* height: 100%; */
  z-index: 0;
  position: absolute;
}

#svg {
  position: absolute;
  z-index: 1;
}
<!DOCTYPE html>
<html>

<head>
  <script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
</head>

<body id="body">
  <div id="zoom-controls" style='position:fixed'>
    <button id="zoom_in">+</button>
  </div>
  <svg id="svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 0 0" preserveAspectRatio="none"></svg>
</body>

</html>

1 个答案:

答案 0 :(得分:2)

您的按钮容器位于所有内容的下方。向其中添加z-index,它将起作用。

.draggable {
  cursor: move;
}

.pdf-page-canvas {
  display: block;
  margin: 5px auto;
  border: 1px solid rgba(0, 0, 0, 0.2);
  z-index: 0;
}

.canvas_container {
  width: 100%;
  /* height: 100%; */
  z-index: 0;
  position: absolute;
}

#zoom-controls {
  z-index: 3;
}

#svg {
  position: absolute;
  z-index: 1;
}
<body>
    <div id="zoom-controls" style='position:fixed'>
        <button id="zoom_in">+</button>
    </div>
    <svg id='svg' xmlns="http://www.w3.org/2000/svg" viewBox="0 0 0 0" preserveAspectRatio="none"></svg>
</body>