创建一个HTML页面,使用<script>标记直接引入jQuery文件,插入一张图片,使用jQuery获取该图片元素,并通过事件方法绑定mouseover()、mouseout()事件,实现鼠标移到图片上加红色边框,鼠标从图片上移出时去除边框。
时间: 2023-12-03 07:02:40 浏览: 48
以下是HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>使用jQuery绑定鼠标事件</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style type="text/css">
img{
width: 300px;
height: 200px;
border: 2px solid black;
margin-top: 20px;
margin-left: 20px;
margin-bottom: 20px;
}
</style>
</head>
<body>
<img src="https://picsum.photos/300/200" alt="图片">
<script>
$(document).ready(function(){
$("img").mouseover(function(){
$(this).css("border", "2px solid red");
});
$("img").mouseout(function(){
$(this).css("border", "2px solid black");
});
});
</script>
</body>
</html>
```
解释:
1. 在head标签中引入jQuery文件:
```html
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
```
2. 在body标签中插入一张图片:
```html
<img src="https://picsum.photos/300/200" alt="图片">
```
3. 在script标签中使用jQuery的mouseover()和mouseout()方法,绑定鼠标移入和移出事件,并设置边框颜色:
```html
<script>
$(document).ready(function(){
$("img").mouseover(function(){
$(this).css("border", "2px solid red");
});
$("img").mouseout(function(){
$(this).css("border", "2px solid black");
});
});
</script>
```
注意:`$(document).ready()`方法用于在文档加载完成后执行代码,确保页面元素都已经加载完毕,避免出现找不到元素的问题。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)