<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() { //動(dòng)態(tài)添加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; //獲取發(fā)生事件 event 兼容 =====1
var target = ev.target || ev.srcElement; //獲取真正被觸發(fā)的元素 =====2
if (target.nodeName.toLocaleLowerCase() == 'li') {
//判斷target是否是所需要的元素 正是因?yàn)檫@個(gè)判斷 我們可以得到任何想要的元素 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?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.
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.
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