您的位置:首页 > Web前端 > JavaScript

原生js实现自定义右键菜单进行颜色切换

2019-04-20 16:30 495 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Flynn_curry/article/details/89419385

简单来说就是js中用了个2重闭包,至于菜单,和导航栏的下拉框一样,不用时隐藏,使用时显示。

直接上代码了,比较简单。

效果图:

 

html:

[code]<!DOCTYPE html>
<html>
<head>
<title>practice</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="test13.css">
</head>
<body>
<div id="container" class="center-spacearound" style="flex-wrap: wrap;">
<div class="box center-all">右键改变颜色</div>
<div class="box center-all">右键改变颜色</div>
<div class="box center-all">右键改变颜色</div>
<div class="box center-all">右键改变颜色</div>
<ul class="rightmenu">
<li class="center-all rightmenu-li" style="background-color: green;">绿色</li>
<li class="center-all rightmenu-li" style="background-color: blue;">蓝色</li>
<li class="center-all rightmenu-li" style="background-color: pink;">粉色</li>
<li class="center-all rightmenu-li" style="background-color: brown;">棕色</li>
</ul>
</div>
<script type="text/javascript" src="test13.js"></script>
</body>
</html>

 

 

css:

[code]/*------------------------公共样式表----------------------------*/
* {
margin: 0px;
padding: 0px;
border: 0px;
}
.center-spacearound {
display: flex;
align-items: center;
justify-content: space-around;
}
.center-all {
display: flex;
align-items: center;
justify-content: center;
}
/*------------------------功能样式表----------------------------*/
#container {
width: 900px;
height: 300px;
margin: 15px auto;
background-color: yellow;
border-radius: 15px;
z-index: 0;
}
.box {
width: 200px;
height: 200px;
background-color: red;
color: white;
font-size: 26px;
cursor: pointer;
z-index: 1;
}
.rightmenu {
display: none;
position: absolute;
/*margin-top: 109px;*/
z-index: 2;
cursor: pointer;
}
.rightmenu-li {
width: 154px;
height: 41px;
border-bottom: 1px solid #DDDDDD;
color: white;
}

 

 

js:

[code]var namelist = ["green", "blue", "pink", "brown"];
var boxitem = document.getElementsByClassName("box");
var rightmenu = document.getElementsByClassName("rightmenu");
var rightli = document.getElementsByClassName("rightmenu-li");
for (var i = 0; i < boxitem.length; i++) {
(function(i){
boxitem[i].oncontextmenu = function(obj) {
if (!obj) obj = event || window.event;
if (obj.button==2) {
obj.preventDefault();
// console.log(obj.clientX);
// console.log(obj.clientY);
rightmenu[0].style.display = "block";
rightmenu[0].style.left = obj.clientX + "px";
rightmenu[0].style.top = obj.clientY + "px";
for (var j = 0; j < rightli.length; j++) {
(function(j){
rightli[j].onclick = function() {
boxitem[i].style.backgroundColor = namelist[j];
}
})(j)
}
}
}
})(i)
}
window.onclick = function() {
rightmenu[0].style.display = "none";
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: