我想在原有的练习上扩展一下,麻烦老师解答,谢谢!
来源:11-2 编程练习
V仔兽7022
2019-06-06 11:00:38
想要实现点击【添加元素】后的li依旧有鼠标事件;
想要实现当鼠标点击li,颜色变为pink,并且鼠标移开后依旧是pink,若是没有点击li,则鼠标移出后是#cdffc0.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
html,
body {
margin: 0;
padding: 0;
}
div:not(:nth-of-type(2)) {
width: 500px;
height: 100%;
background-color: #00c4ff7a;
margin: 0 auto;
}
/*ul默认有外边距*/
ul {
width: 300px;
height: 100%;
background-color: #f9c3e6d6;
list-style: none;
/*清除默认边距*/
margin: 0;
padding: 0;
margin: 20px auto;
margin-bottom: 30px;
}
li {
width: 200px;
height: 30px;
line-height: 30px;
margin: 30px auto;
background-color: #cdffc0;
}
</style>
</head>
<body>
<div id="box">
<button id="btnAdd">添加元素</button>
<button id="btnRemove">删除元素</button>
<ul id="list">我是ul
<li>我是li1</li>
<li>我是li2</li>
<li>我是li3</li>
</ul>
</div>
<script type="text/javascript">
var ul1=document.getElementById("list");
var btnAdd=document.getElementById("btnAdd");
var btnRemove=document.getElementById("btnRemove");
// 添加
btnAdd.onclick=function(){
var list1=ul1.querySelectorAll("li");
var newli=document.createElement("li");
var litext=document.createTextNode("我是li"+(list1.length+1));
newli.appendChild(litext);
ul1.appendChild(newli);
}
// 删除
btnRemove.onclick=function(){
var list2=ul1.querySelectorAll("li");
var lilast=list2[list2.length-1]
lilast.outerText='';
}
// 鼠标事件
var licoll=document.getElementsByTagName("li");
for(var i=0;i<licoll.length;i++){
licoll[i].onmouseover=function(){
this.style.backgroundColor="purple";
}
licoll[i].onmouseout=function(){
this.style.backgroundColor="#cdffc0";
}
}
licoll[i].onclick=function(){
this.style.backgroundColor="pink";
this.onmouseout=function(){
this.style.backgroundColor="pink";
}
}
</script>
</body>
</html>
1回答
同学你好,1、 最简单的方式是在创建新的元素后 ,给新元素绑定事件:
2、(1)for循环的结束的花括号是错误的哦,没有把点击事件包裹进去。
(2)关于这个,老师这里给你提供一个思路,可以尝试下哦,在点击的时候,给当前点击的这个元素添加一个属性,然后在鼠标移出的时候,判断当前这个元素,是否有这个输入,若是有的话,就不变色,没有的话,变回#cdffc0.
希望能帮助到你,欢迎采纳。
祝学习愉快!
相似问题