超棒的自定义右键选项。纯 CSS 和 JS 实现。
演示
视频教程 -
让我们开始编程吧
由 Mux 赞助的 DEV 全球展示挑战赛:展示你的项目!
您好,很高兴您能来。我是 Kunaal,今天我们将学习如何创建自定义右键选项。您可以在下方看到演示。
演示
视频教程 -
如果您觉得这篇文章难以理解,或者需要更详细的解释,可以观看视频教程。
如果您喜欢这个视频教程,请考虑订阅我的YouTube频道。
让我们开始编程吧
在 HTML 文件中的<body>标签下写入
h1 class="text">right click</h1>
<div class="options">
<h1 class="title">pages</h1>
<hr>
<ul class="link-container">
<li class="link-item">
<a href="#" class="link">home</a>
</li>
<li class="link-item">
<a href="#" class="link">projects</a>
</li>
<li class="link-item">
<a href="#" class="link">about us</a>
</li>
<li class="link-item">
<a href="#" class="link">contact us</a>
</li>
</ul>
</div>
CSS
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
width: 100%;
min-height: 100vh;
background: #ffa462;
font-family: roboto, sans-serif;
display: flex;
place-items: center;
}
.text{
text-transform: uppercase;
font-size: 250px;
text-align: center;
color: #000;
opacity: .25;
user-select: none;
word-wrap: break-word;
}
.options{
width: 200px;
height: 250px;
background: #ebebeb;
position: absolute;
top: 0;
left: 0;
border-radius: 10px;
padding: 20px 0;
border: 2px solid #f0efef;
box-shadow: 0 20px 20px rgba(0, 0, 0, 0.3);
user-select: none;
display: none;
}
.title{
padding: 0 20px;
font-weight: 400;
text-transform: capitalize;
color: #565656;
font-size: 25px;
opacity: .7;
}
.options hr{
padding: 0 20px;
opacity: .1;
border: .5px solid #000;
border-radius: 10px;
margin: 10px;
}
.link-item{
list-style: none;
width: 100%;
height: 30px;
margin: 2px 0;
line-height: 30px;
display: flex;
}
.link{
color: #969696;
font-weight: 300;
text-transform: capitalize;
text-decoration: none;
width: 100%;
padding: 0 20px;
}
.link:hover{
background-color: #fff;
}
最后还有一小段JS代码。
const options = document.querySelector('.options');
window.oncontextmenu = (e) => {
e.preventDefault();
if(e.y + 250 <= window.innerHeight){
options.style.top = `${e.y}px`;
} else{
options.style.top = `${e.y - 250}px`;
}
if(e.x + 200 <= window.innerWidth){
options.style.left = `${e.x}px`;
} else{
options.style.left = `${e.x - 200}px`;
}
options.style.display = 'block';
}
window.onclick = () => {
if(options.style.display === 'block'){
options.style.display = null;
}
}
希望你都理解了。如果你有任何疑问,或者发现我犯了任何错误,或者有任何建议,请随时在评论区留言。
文章来源:https://dev.to/themodernweb/how-to-make-custom-right-click-options-pure-css-and-js-53e8如果你对编程感兴趣,想了解我这个15岁的少年是如何编写代码并设计出这些作品的,可以关注我的Instagram账号。我也计划在Instagram上分享我的游戏开发成果。