<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>函数传参</title>
</head>
<style type="text/css">
#div1{
width: 200px;
height: 200px;
border: red solid 2px;
background-color: red;
background-size:cover ;
}
</style>
<script type="text/javascript">
function set(set1,set2){
var js_1=document.getElementById('div1');
js_1.style[set1]=set2;
}
</script>
<body>
<input type="button" value="变绿" onclick="set('backgroundColor','green')" />
<input type="button" value="变宽" onclick="set('width','400px')" />
<input type="button" value="变高" onclick="set('height','400px')" />
<input type="button" value="向右" onclick="set('margin-left','200px')" />
<div id="div1">
</div>
</body>
</html>
先注意下 单双引号的位置
- 单引号:var js_1=document.getElementById(‘div1’);
- 单引号:οnclick=”set(‘width’,’400px’)”
- 双引号 :一般我不在 js中用双引号,除非特殊情况例
<input type="button" onclick="alert("1")">-------------------不正确
<input type="button" onclick="alert('1')">-------------------正确
即 代码内部有单引号时必须用双引号,其他情况本人一般都用单引号
- 加引号的是字符串常量(例如 id ,class)
- 不加引号的是变量(还有基本所有形参,和一些非实参)、、
资历尚浅,或许有我不知道的,谢谢评价
送给 一段代码 ,上面有我说的情况,代码实现,不做解释
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
div {width:200px; height:200px; margin:20px; float:left; background:yellow; border:10px solid black; filter:alpha(opacity:30); opacity:0.3;}
</style>
<script>
window.onload=function ()
{
var oDiv1=document.getElementById('div1');
oDiv1.onmouseover=function ()
{
startMove(this, 'opacity', 100);
};
oDiv1.onmouseout=function ()
{
startMove(this, 'opacity', 30);
};
};
function getStyle(obj, name)
{
if(obj.currentStyle)
{
return obj.currentStyle[name];
}
else
{
return getComputedStyle(obj, false)[name];
}
}
function startMove(obj, attr, iTarget)
{
clearInterval(obj.timer);
obj.timer=setInterval(function (){
var cur=0;
if(attr=='opacity')
{
cur=parseFloat(getStyle(obj, attr))*100;
}
else
{
cur=parseInt(getStyle(obj, attr));
}
var speed=(iTarget-cur)/6;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(cur==iTarget)
{
clearInterval(obj.timer);
}
else
{
if(attr=='opacity')
{
obj.style.filter='alpha(opcity:'+(cur+speed)+')';
obj.style.opacity=(cur+speed)/100;
}
else
{
obj.style[attr]=cur+speed+'px';
}
}
}, 30);
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>