首页 > 解决方案 > 放置一个按钮,使其不会随内容滚动

问题描述

我有这个代码:

pre[class*="language-"] {
  top: 0;
  position: relative;
  border-radius: 3px;
}

#copybutton {
  position: absolute;
  right: 1em;
  top: 1em;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  border: 0px transparent;
  font-size: 0.725rem;
  padding: 3px;
  border-radius: 5px;
  background-color: #ebebeb;
  transition: background-color 0.25s ease-in-out;
}
<link href="https://prismjs.com/themes/prism.css" rel="stylesheet">
<script src="https://prismjs.com/prism.js"></script>
<pre class="language-js">
  <button id="copybutton">Copy</button>
  <code>const name = "" //a really really really really really really really really really really really really really really really really long </code>
</pre>

我想定位按钮,以便当用户水平滚动代码时,按钮不应该移动它的位置。但是当用户滚动页面(而不是代码)时,它应该移动。CSS 和 JS 答案表示赞赏。请不要在 jQuery 中回答。

标签: javascripthtmlcss

解决方案


添加一个 wrapper div,将设为相对而不是pre自身,然后将按钮从pre.

.code-display-wrapper {
  position: relative;
}

pre[class*="language-"] {
  border-radius: 3px;
}

#copybutton {
  position: absolute;
  right: 1em;
  top: 1em;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  border: 0px transparent;
  font-size: 0.725rem;
  padding: 3px;
  border-radius: 5px;
  background-color: #ebebeb;
  transition: background-color 0.25s ease-in-out;
}
<link href="https://prismjs.com/themes/prism.css" rel="stylesheet">
<script src="https://prismjs.com/prism.js"></script>

foo<br>foo<br>foo<br>foo<br>

<div class="code-display-wrapper">
  <button id="copybutton">Copy</button>
  <pre class="language-js">
    <code>const name = "" //a really really really really really really really really really really really really really really really really long </code>
  </pre>
</div>

foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>


推荐阅读