JavaScript 事件:
事件指的就是当某些组件执行了某些操作后,会触发某些代码的执行。
常用的事件:
属性 | 触发时机 |
---|
onabort | 图像加载被中断 | onblur | 元素失去焦点 | onchange | 用户改变域的内容 | onclick | 鼠标点击某个对象 | ondblclick | 鼠标双击某个对象 | onerror | 当加载文档或图像时发生某个错误 | onfocus | 元素获得焦点 | onkeydown | 某个键盘的键被按下 | onkeypress | 某个键盘的键被按下或按住 | onkeyup | 某个键盘的键被松开 | onload | 某个页面或图像被完成加载 | onmousedown | 某个鼠标按键被按下 | onmousemove | 鼠标被移动 | onmouseout | 鼠标从某元素移开 | onmouseover | 鼠标被移到某元素之上 | onmouseup | 某个鼠标按键被松开 | onreset | 重置按钮被点击 | onresize | 窗口或框架被调整尺寸 | onselect | 文本被选定 | onsubmit | 提交按钮被点击 | onunload | 用户退出页面 |
事件操作
绑定事件
方式一: 通过标签中的事件属性进行绑定。
<body>
<img id="img" src="https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1582373193,2567665585&fm=26&gp=0.jpg">
<br/>
<button id="up" onclick="up()">上一张</button>
<button id="down" onclick="down()">下一张</button>
</body>
<script>
function up() {
let img = document.getElementById("img");
img.setAttribute("src", "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1582373193,2567665585&fm=26&gp=0.jpg")
}
function down() {
let img = document.getElementById("img");
img.setAttribute("src", "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic4.58cdn.com.cn%2Fp1%2Fbig%2Fn_v26f22be8b05a74c42b8f9dfb859480186.jpg%3Fw%3D425%26h%3D320&refer=http%3A%2F%2Fpic4.58cdn.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1618451421&t=0310ddbd6f7cd840299b10dd314572c8")
}
</script>
方式二: 通过 DOM 元素属性绑定。
<body>
<img id="img" src="https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1582373193,2567665585&fm=26&gp=0.jpg">
<br/>
<button id="up">上一张</button>
<button id="down">下一张</button>
</body>
<script>
function up() {
let img = document.getElementById("img");
img.setAttribute("src", "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1582373193,2567665585&fm=26&gp=0.jpg")
}
let s = document.getElementById("up");
s.onclick = up;
function down() {
let img = document.getElementById("img");
img.setAttribute("src", "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic4.58cdn.com.cn%2Fp1%2Fbig%2Fn_v26f22be8b05a74c42b8f9dfb859480186.jpg%3Fw%3D425%26h%3D320&refer=http%3A%2F%2Fpic4.58cdn.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1618451421&t=0310ddbd6f7cd840299b10dd314572c8")
}
let x = document.getElementById("down");
x.onclick = down;
</script>
|