<input type="text" id="txt" placeholder="输入要添加的文本" />
<button id="btn">加 </button>
<ul id="ul">
<li>11111</li>
<li>22</li>
<li>3333</li>
<li>4444</li>
</ul>
<script type="text/javascript">
var ul = document.getElementById("ul");
var lis = ul.getElementsByTagName('li');
var btn = document.getElementById("btn");
btn.onclick = function() { //动态添加li
var txt = document.getElementById("txt"),
txtValue = txt.value,
ali = document.createElement("li");
console.log(txt.value);
ali.innerHTML = txtValue;
ul.appendChild(ali);
}
ul.onmouseover = function(ev) {
var ev = ev || window.event; //获取发生事件 event 兼容 =====1
var target = ev.target || ev.srcElement; //获取真正被触发的元素 =====2
if (target.nodeName.toLocaleLowerCase() == 'li') {
//判断target是否是所需要的元素 正是因为这个判断 我们可以得到任何想要的元素 a li td 等等
target.style.background = "red";
}
}
ul.onmouseout = function(ev) {
var ev = ev || window.event;
var target = ev.target || ev.srcElement;
if (target.nodeName.toLocaleLowerCase() == 'li') {
target.style.background = "";
}
}
</script>
How do you understand the writing of the codes marked 1 and 2 ? I can’t understand = =Where does the api
come from?给我你的怀抱2017-06-28 09:30:50
ev is the parameter of the event. ev contains the parameters when the event is triggered. For example, the ev of the click event contains ev.pageX, ev.pageY, the keydown event contains ev.keyCode, etc. In IE, ev is global. It can be obtained through window.event, which is passed in as a parameter in other browsers.
大家讲道理2017-06-28 09:30:50
ev in
function is the abbreviation of event, that is, event. The event interface belongs to the browser side implementation.
To put it simply: window/event is a global variable. As long as it is executed in the browser, this variable exists by default.
欧阳克2017-06-28 09:30:50
Mainly dealing with browser compatibility
For example, 2
old IE browsers, or the elements corresponding to events need to use ev.srcElement, but now browsers only need to use ev.target