您的位置:首页 > Web前端 > JavaScript

一个简单且丑陋的js切换背景图片基础示例

2014-07-22 20:20 696 查看
不多说,直接上代码,非常基础的一个原生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{ width: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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: