JS笔记一:动态修改css样式

时间:2022-02-07 16:27:48

---恢复内容开始---

最近在学习CSS/JS的样式,两个合学习一起学习,加深JS的书写和了解。

一、通过Javasript修改图片大小

通过函数来传递图片id,height,width,使用document.ElementByID来控制图片的大小,也就通过id 控制图片,之前有学过一句document.getElementByTagName('img')[0],这里也可以通过这种方式来设定固定的图片。

在前一篇有写过如何写这个图片的样式,在图片的基础加上能够放大以及回放图片,先来看看这个的分段JS代码介绍

      var status = true;//状态设置
        function changeSize(imge,height,width)
         {
var imgH =height; //获取图片的高度
var imgW =width; //获取图片的宽度
            if(status){
//图片为正常状态,设置图片宽高为现在宽高的2倍
status = false;//把状态设为放大状态
document.getElementById(imge).height= imgH*2;
document.getElementById(imge).width= imgW*2;
}else{
//图片为放大状态,设置图片宽高为现在宽高的二分之一
status = true;//把状态设为正常状态
document.getElementById(imge).height=imgH/2;
document.getElementById(imge).width= imgW/2;
}
changeStyle();//修改div样式的函数 }

第一个函数changeSize为获取 id,width,height.在判断状态那里,status设置true为初始态,进入if,先将status 设置为放大状态,通过document.ElementById().height/width来控制图片缩放。

二、通过JS修改CSS样式

学习了四种如何修改CSS样式,第四种外联样式,因为我觉得较少使用所以就没有插入进来学习,其他三种都有放进来,同时学习了解。

 function changeStyle() {
  var obj = document.getElementById('change'); 
if(status){
// obj.setAttribute("class", "polaroid");
// obj.style.width= "250px";
obj.style.cssText="width:250px;";
}else{
// obj.setAttribute("class", "polaroid1");
// obj.style.width= "500px";
obj.style.cssText="width:500px;"; }
}

在上面展示的三种中,第一种要写两个CSS样式,因为它是直接替换掉一整个class,而二三种比较便利,直接替换其中一个样式。

事实上这两个函数是可以整合在一起的,但是为了方便了解那部分是什么作用,我在学习过程种就分开写了,但是写代码就要不断的优化。

附录完整代码

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>change photo</title>
<style type="text/css">
body
{
margin:30px;
background-color: #E9E9E9;
text-align: center;
} div.polaroid
{
width:250px;
padding:10px 10px 20px 10px;
border:1px solid #BFBFBF;
box-shadow: 2px 2px 3px #aaaaaa; }
div.polaroid1
{
width:500px;
padding:10px 10px 20px 10px;
border:1px solid #BFBFBF;
box-shadow: 2px 2px 3px #aaaaaa; } </style>
</head>
<body align="center"> <div id="change" class="polaroid ">
<img id="first" src="C:\Users\12078\Desktop\11.jpg" alt="" width="250px" height="200px" onclick="changeSize(id,height,width); ">
<p >远方.</p>
</div> <script type="text/javascript">
var status = true;
function changeSize(imge,height,width)
{
var imgH =height; //获取图片的高度
var imgW =width; //获取图片的宽度
if(status){
//图片为正常状态,设置图片宽高为现在宽高的2倍
status = false;//把状态设为放大状态
document.getElementById(imge).height= imgH*2;
document.getElementById(imge).width= imgW*2;
}else{
//图片为放大状态,设置图片宽高为现在宽高的二分之一
status = true;//把状态设为正常状态
document.getElementById(imge).height=imgH/2;
document.getElementById(imge).width= imgW/2;
}
changeStyle(); }
function changeStyle() {
  var obj = document.getElementById('change'); 
if(status){ obj.style.cssText="width:250px;";
}else{ obj.style.cssText="width:500px;"; }
}
</script> </body>
</html>