Learned about bubbling events, typed the code and made small details changes based on online articles. I have a question:
1. The ultimate goal is to change the color when the mouse moves up. How to achieve this?
2. How to solve the problem that when the next li element is clicked, the color of the previously clicked element is restored?
Please tell me your ideas and the methods you will use. I will write the rest myself. I want to exercise my ability to type code. Thank you!
PS: It’s easy to read a book, but it’s confusing to write code by yourself, hey!
HTML code is as follows:
<ul id="color">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
JS code:
(function () {
var color_list = document.getElementById('color');
color_list.addEventListener('click',changeColor);
function changeColor(e) {
var x = e.target;
if(x.nodeName.toLowerCase() === 'li')
x.style.backgroundColor = 'red';
// 最终目的要实现鼠标移动上去就变色?
// 另外,如何解决点击下一个li元素,上一个点击的元素颜色还原?
}
})();
1. If it can be solved with CSS, JS is not needed. The idea of the question is: hover pseudo-class can solve this problem.
2, but your code is a click event.. It’s a bit wrong. Well, since I have written an event proxy, I will write a lower one and directly operate the li when there are not many li
Do you know closure? In order not to pollute global variables and use closures, the first way to write it is to directly clear the color of all li and add color to the currently clicked li.
For the second way of writing, I wrote it directly inside. I won’t repeat the same code for element acquisition and closure outside.
The second method is to clear the previous one and add color to the current li. In comparison, the performance of the second method is slightly better, and the first method is simpler to understand.
ps: However, I still recommend the event proxy writing method.
Why not css~
You can use mouseenter and mouseout events
To change the color when the mouse is moved up, you mainly need to use css, and the pseudo class:hover can be done.
Two ideas are provided if clicked. 1. Restore the color of all li under ul, and change e.target to red.
2. Click to save the previous target, click to restore the color of the previous target, and the current target becomes red
Move the mouse up to change the color. Why not use the hover event? You can search for hover.
For all those who move up to xx and down to yy, first consider using the hover pseudo-class of CSS;
You save your default attributes in a class name, and save the changed attributes in another class name. During the click callback,
$(this)
remove the default class and add the change class, and then traverse its sibling elements to find the change class. , after finding it, remove the change class and add the default class, it should be fine~hover(function(){
},function(){
})