首页 > 其他分享 >通过JS设置CSS样式

通过JS设置CSS样式

时间:2023-07-21 22:46:44浏览次数:45  
标签:box const 样式 classList JS onclick btn CSS

读取元素样式

在JS中可以使用getComputedStyle() 读取元素样式

官网摘要
Window.getComputedStyle()方法返回一个对象,该对象在应用活动样式表并解析这些值可能包含的任何基本计算后报告元素的所有 CSS 属性的值。私有的 CSS 属性值可以通过对象提供的 API 或通过简单地使用 CSS 属性名称进行索引来访问。

语法

let style = window.getComputedStyle(element, [pseudoElt]);

示例

const box =  document.getElementById("box")
const btn = document.getElementById("btn")

btn.onclick = ()=>{
    const w = getComputedStyle(box).width
    console.log(parseInt(w));
}

通过以上操作可以在控制台输出元素的宽度

修改元素样式

1.直接修改

修改元素样式的方法为,在选中元素之后按如下格式修改
元素.style.样式名称 = '样式值'
如果没有特别说明,示例中的HTML代码为同一段
HTML代码

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet"  href="./index.css">
    <script defer src="./index.js"></script>

</head>
<body>
    <div class="box"></div>
    <button type="button" id="btn">按钮</button>
</body>
</html>

CSS代码

.box{
    width: 100px;
    height: 100px;
    background-color: black;
}

.box1{
    width: 300px;
    height: 400px;
    background-color: #6A5ACD;
}
.box2{
    border: 2px red solid;
}

设置完成之后效果如下:
image

JS代码

const box =  document.getElementById("box")
const  box = document.querySelector(".box")

btn.onclick = ()=>{
    box.style.backgroundColor = '#dfcacf'
}
2.通过className修改

修改方式如下
JS代码

const btn = document.getElementById("btn")
const  box = document.querySelector(".box")

btn.onclick = ()=>{
    box.className = "box1"
}

方式2相比与方式一有所改善,但是当同时需要添加多个样式的收依旧存在不便,方法三中的方式解决了这个问题

3.通过classList修改
  • 添加属性
btn.onclick = ()=>{
    box.classList.add('box2')
}

  • 移除属性
btn.onclick = ()=>{
    box.classList.remove('box')
}
  • 切换属性
btn.onclick = ()=>{
    box.classList.toggle('box1')//只能切换一个元素
}
  • 替换属性
    使用box1替换box
btn.onclick = ()=>{
    box.classList.replace('box','box1')
}
  • 检查是否包含某个类
btn.onclick = ()=>{
    const is = box.classList.contains('box')
    console.log(is);
}

关于classList的其它具体内容请查看官网介绍 官网链接

以上就是今天的记录

标签:box,const,样式,classList,JS,onclick,btn,CSS
From: https://www.cnblogs.com/fuqiuhong/p/17572495.html

相关文章

  • css基础-float浮动
    什么是浮动创建浮动框,将其移动左或者右边,直到碰到左边缘或右边缘。特性:浮动元素会脱离标准流,浮动的盒子不会保留白原来位置一行内显示,顶端对齐行内元素加了浮动元素都会具有行内块元素,无需转换,可以设置高度和宽度。为什么要用浮动网页布局本质就是摆盒子,传统网页布局方式:a)通过......
  • js语法
     const[lon,lat]=coord.split(',').map(Number); 原理解释使用了解构赋值和数组映射的方式从坐标字符串(coord)中提取经度(lon)和纬度(lat)值,并将它们从字符串转换为数字。 1、coord.split(','):使用逗号,作为分隔符,将坐标字符串coord拆分为一个字符串数组。例如,如果......
  • vue 使用vue-json-viewer 展示 JSON 格式数据
    为什么需要Vue-json-viewer在前端开发中,我们经常需要处理JSON数据。然而,JSON数据一般是以字符串的形式来传递,难以直观地查看、理解和调试,这阻碍了我们开发工作的进程。Vue-json-viewer组件正是为了解决这个问题而生。安装vue-json-viewer插件npminstallvue-json-viewer--sa......
  • struts2 jsonplugin includeProperties中对list集合的正则配置
     1、listAttachment.*\.realName 和listAttachment.* 效果一样,元素中所有的属性都json化了   "listAttachment":[{"encodedRealName":"%E8%AE%A1%E5%88%92%E4%BB%BB%E5%8A%A1%E4%B9%A6%E5%88%97%E8%A1%A820111223102409.xls","id":"408080b7......
  • (转)JS判断文件大小
    第一种是应用ActiveX控件的实现,例如:Javascript代码<scripttype="text/javascript">functiongetFileSize(filePath){varfso=newActiveXObject("Scripting.FileSystemObject");alert("文件大小为:"+fso.GetFile(filePath).s......
  • How to pass new hidden value to backing bean in JSF(JSF 隐藏域传值到后台)
    JSF隐藏域传值到后台 Insomecases,youmayneedtopassanewhiddenvaluetoabackingbean.Generally,therearetwoways:1.HTMLTag+getRequestParameterMap()RenderhiddenfieldwithplainHTMLinput,hard-codednewhiddenvalueandaccessinbackingbe......
  • jsp 超链接带系统前缀
    如: <a href="www.iteye.com">iteye</a> 网页生成后点击此超链接,始终有如http://localhost:8080的前缀,变成http://localhost:8080/www.iteye.com  解决:加上http://前缀   <a href="http://www.iteye.com">iteye</a> ......
  • vue3如何正确设置 Tailwind CSS
    1.创建vue3项目npminitvue@latest需要配置的选择YES 2.切换到项目newProject目录下 npminstall下载依赖包 3.安装tailwind及其依赖项(PostCSS和自动前缀)npminstall-Dtailwindcss@latestpostcss@latestautoprefixer@latest4.创建tailwind.config.js文件......
  • NextJs 中使用Next-Auth
    NextJs中使用Next-Auth本篇讨论的范畴是Azureb2c做为provider,token的类型是jwttoken.我们讨论在Azureb2c认证完后,由Next-Auth负责认证的过程。BasicConceptToken这个就是cookie,它的名字是非https是next-auth.session-token,如果是https则是__Secure-next-auth.sessio......
  • css-demo
    1、文字放大缩小<!DOCTYPEhtml><html><head><metacharset="utf-8"><style>@keyframesscaleDraw{0%{transform:scale(......