学这个的时候 https://zh.javascript.info/default-browser-action。
做动态图片的练习题,发现上面有通过id直接绑定事件的。也试着搞了个。
<!DOCTYPE HTML>
<html>
<head>
<title>Gallery</title>
<meta charset="utf-8">
<style>
#largeImg {
border: solid 1px #ccc;
width: 550px;
height: 400px;
padding: 5px;
}
#thumbs{
display: flex;
}
#thumbs li {list-style-type:none;}
#thumbs a {
border: solid 1px #ccc;
width: 100px;
height: 100px;
padding: 3px;
margin: 2px;
float: left;
}
#thumbs a:hover {
border-color: #FF9900;
}
</style>
</head>
<body>
<p><img id="largeImg" src="https://en.js.cx/gallery/img1-lg.jpg" alt="Large image"></p>
<ul id="thumbs">
<!-- the browser shows a small built-in tooltip on hover with the text from "title" attribute -->
<li>
<a href="https://en.js.cx/gallery/img2-lg.jpg" title="Image 2"><img src="https://en.js.cx/gallery/img2-thumb.jpg"></a>
</li>
<li>
<a href="https://en.js.cx/gallery/img3-lg.jpg" title="Image 3"><img src="https://en.js.cx/gallery/img3-thumb.jpg"></a>
</li>
<li>
<a href="https://en.js.cx/gallery/img4-lg.jpg" title="Image 4"><img src="https://en.js.cx/gallery/img4-thumb.jpg"></a>
</li>
<li>
<a href="https://en.js.cx/gallery/img5-lg.jpg" title="Image 5"><img src="https://en.js.cx/gallery/img5-thumb.jpg"></a>
</li>
<li>
<a href="https://en.js.cx/gallery/img6-lg.jpg" title="Image 6"><img src="https://en.js.cx/gallery/img6-thumb.jpg"></a>
</li>
</ul>
</body>
<script>
function closest(el, selector) {
var matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
while (el) {
if (matchesSelector.call(el, selector)) {
break;
}
el = el.parentElement;
}
return el;
}
function handleLink(href) {
largeImg.src = href;
return false;
}
thumbs.onclick = function(event) {
// let target = event.target.closest('a');
let target = closest(event.target,'a'); //兼容ie
if (target) {
return handleLink(target.getAttribute('href'));
}
};
</script>
</html>
妮玛,好像很方便啊,ie也能支持,那为什么还要用原生getid或者用juery呢。哈哈哈,js果然博大精深。