javascript - 放置一个按钮,使其不会随内容滚动
问题描述
我有这个代码:
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 中回答。
解决方案
添加一个 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>
推荐阅读
- android - 设备之间的语音通信示例?
- node.js - node.js 控制台异步应用“最佳实践”
- python - 非标准端口的 Python HTTPServer SSL 握手挂起
- android - Android 推送通知关闭:它是如何在内部工作的?
- python - Python Spacy 的 Lemmatizer:以最高效率获取所有引理选项
- javascript - 量角器:在以前在终端中工作的 config.js 文件上收到错误消息
- python - 可以同时播放 1xFHD 和 2-3 个较小视频的 omxplayer 实例有多少?
- lua - Wireshark 2.6.4 dissector 对象类型“Tvb”没有此类功能/属性
- c++ - 使用考虑翻转或包装 std::map 中键值的键
- google-chrome - 问:是否可以在 Chrome 扩展程序中安全地解密敏感信息(带有 ftp 用户并通过的 URL)?