背景图只有一张
第一种方法
<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8"> <title></title> <style> #btn{ background: url("1.png"); width: 120px; height: 30px; border-style: none; } </style></head><body><button id="btn" onmouseover="changeImg()" onmouseout="changeImg()">切换图片</button><script> var m = 1; function changeImg(){ var img = document.getElementById("btn"); if(m == 1){ img.style.backgroundPosition = ‘0px -30px‘; m = 2; }else{ img.style.backgroundPosition = ‘0px 0px‘; m = 1; } }</script></body></html> 第二种方法 前面与第一种方法类似,这种方法是通过display属性实现的
<body> <input type="button" id="btn" value="切换图片" onmouseover="changeImg()" onmouseout="changeImg()"> <input type="button" id="btn1" value="切换图片" style="display: none" onmouseover="changeImg()" onmouseout="changeImg()"><script> function changeImg(){ var btn = document.getElementById("btn"); var btn1 = document.getElementById("btn1"); if(btn1.style.display == "none"){ btn1.style.display = "block"; btn.style.display = "none"; }else{ btn.style.display = "block"; btn1.style.display = "none"; } }</script></body>第三种方法与第二种方法基本雷同
<input type="button" id="btn" value="切换图片" onmouseover="changeImg()" onmouseout="changeImg()"><input type="hidden" id="btn1" value="切换图片" onmouseover="changeImg()" onmouseout="changeImg()"><script> function changeImg(){ var btn = document.getElementById("btn"); var btn1 = document.getElementById("btn1"); if(btn.type == "button"){ btn1.type = "button"; btn.type = "hidden"; }else{ btn.type = "button"; btn1.type = "hidden"; } }</script>第四种方法是用jQuery实现的html文件:
<html><head lang="en"> <meta charset="UTF-8"> <title></title> <script src="jquery-3.1.0.min.js"></script> <script src="jcss.js"></script> <link rel="stylesheet" type="text/css" href="jcss.css"></head><body> <button></button></body></html>引入文件的时候要注意,把下载的jquery文件放在前面
css文件:
.img1,.img2{ background-image: url("1.png"); width: 120px; height: 30px; border-style: none;}.img2{ background-position: 0px -30px;} js文件:
$(document).ready(function(){ $("button").addClass("img1"); $("button").mouseover(function () { $("button").addClass("img2"); $("button").removeClass("img1"); }).mouseout(function(){ $("button").addClass("img1"); $("button").removeClass("img2"); })})
时间: 2024-10-01 19:55:06