不多说,直接上代码,非常基础的一个原生js切换元素背景图片范例
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>原生JS范例</title> <script type="text/javascript"> function changeBg(){ var domobj = document.getElementById('bg');//获取dom元素 var bgsrc_a = domobj.getAttribute("data-bg1"); var bgsrc_b = domobj.getAttribute("data-bg2"); domobj.style.backgroundImage='url('+bgsrc_b+')'; //两属性位置互换 domobj.setAttribute('data-bg1',bgsrc_b); domobj.setAttribute('data-bg2',bgsrc_a); } </script> <style type="text/css"> #bg{ 200px; height:80px; background-repeat:no-repeat; background-image:url(http://www.yilewan.com/resource/images/logo.png);} </style> </head> <body> <a href="javascript:;" onclick="changeBg();">点击切换</a> <hr /> <div id="bg" data-bg1='http://www.yilewan.com/resource/images/logo.png' data-bg2='http://www.58game.com/resource/images/logo_58game.png'></div> </body> </html>