经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Java » 查看文章
任何样式,javascript都可以操作,让你所向披靡-云-
来源:cnblogs  作者:-云-  时间:2024/3/25 8:59:27  对本文有异议

前言

习惯了在 css 文件里面编写样式,其实JavaScript 的 CSS对象模型也提供了强大的样式操作能力,
那就随文章一起看看,有多少能力是你不知道的吧。

样式来源

客从八方来, 样式呢, 样式五方来。

chrome旧版本用户自定义样式目录: %LocalAppData%/Google/Chrome/User Data/Default/User StyleSheets。 新版本已经不支持用户自定义样式。

用户代理样式(浏览器默认样式):

至于字体大小,颜色等等,这些都是浏览器默认样式。

前两种样式我们一般不会去修改,绝大部分场景我们都是在操作后面三种样式。

样式优先级

同一个节点的某个属性可能被定义多次,最后哪个生效呢? 这是有一个优先级规则的。

内联样式 > ID选择器 > 类选择器 > 标签选择器

细心的同学会问,伪类呢, important呢, 答案也很简单

  • 伪类 优先级 同 类选择器
  • important 你最大

到这里,各位可能都觉得没问题,那来张图:

截图_20245420045437.png

ID选择器 败给了 样式选择器, 这是因为 CSS 新的 layer (级联层) layer1的优先级更高特性导致的, 后续会有专门的文章介绍。

再提个问题: 如果 layer2 修改为 color: red !important, 那又改显示什么颜色呢。

基本知识准备完毕,那就进入下一个阶段。

操作元素节点上的style属性

  • style属性名是驼峰语法
    想到react给style赋值,是不是呵呵一笑了。
  1. <style>
  2. .div {
  3. background-color: red;
  4. font-size: 30px;
  5. }
  6. </style>
  7. <script>
  8. const el = document.getElementById("test-div");
  9. el.style.backgroundColor = "red";
  10. el.style.fontSize = "30px";
  11. </script>
  • style.cssText 批量赋值
  • important! 也是可以生效的
  1. <div id="test-div">文本</div>
  2. <style>
  3. .div {
  4. background-color: red;
  5. font-size: 30px;
  6. }
  7. </style>
  8. <script>
  9. const el = document.getElementById("test-div");
  10. el.style.cssText ="background-color: green !important; font-size: 40px;"
  11. </script>

那可不可以直接把style赋值一个对象呢? 很不幸,style是一个只读属性,虽然你表面能赋值成功,实际没有任何变化。

  1. // 例如
  2. document.body.style = {color:"red"};

另外你也可以通过attributeStyleMap属性来设置style的值:

  1. const buttonEl = document.querySelector("body");
  2. // 更改背景色
  3. buttonEl.attributeStyleMap.set("background-color", 'red');

目前掌握classList的style.cssText的你,是不有点小嘚瑟呢? 这才哪到哪,还有重头戏。

操作元素节点classList & className属性

className: 操作的是节点的class属性。

对比

属性 方法
className 字符串 字符串具备的方法
classList DOMTokenList 类数组 add, remove, contains, toggle等

没有classList属性之前,我们还需要手动封装类似的方法。 时代的进步真好!

DOMTokenList.toggle

定义: 从列表中删除一个给定的标记 并返回 false 。 如果标记 不存在,则添加并且函数返回 true。

语法: tokenList.toggle(token, force) ;

force参数: 如果force为真,就变为单纯的添加。

用两个按钮分别来演示toggle true和toggle false.

toggle.gif
代码如下:

  1. <div>
  2. <button type="button" id="btnToggleFalse">toggle(false)</button>
  3. <button type="button" id="btnToggleTrue">toggle(true)</button>
  4. </div>
  5. <div id="container">
  6. <div>文字</div>
  7. </div>
  8. <style>
  9. .test-div {
  10. color: red
  11. }
  12. </style>
  13. <script>
  14. const el = container.firstElementChild;
  15. // toggle false
  16. btnToggleFalse.addEventListener("click", function () {
  17. el.classList.toggle("test-div");
  18. });
  19. // toggle true
  20. btnToggleTrue.addEventListener("click", function () {
  21. el.classList.toggle("test-div", true);
  22. })
  23. </script>

操作style节点内容

本质还是Node节点

style标签是不是节点,是,那,就可以为所欲为!!!

  1. <style>
  2. .div {
  3. background-color: red;
  4. font-size: 30px;
  5. }
  6. </style>

拿到文本内容替换,可不可以,当然是可以的。 剑走偏锋!

  1. <div>
  2. <button id="btnReplace" type="button">替换</button>
  3. </div>
  4. <div class="div">
  5. 文本
  6. </div>
  7. <style id="ss-test">
  8. .div {
  9. background-color: red;
  10. font-size: 30px;
  11. }
  12. </style>
  13. <script>
  14. const ssEl = document.getElementById("ss-test");
  15. btnReplace.addEventListener("click", function () {
  16. ssEl.textContent = ssEl.textContent.replace("background-color: red", "background-color: blue")
  17. })
  18. </script>

动态创建style节点

  1. <div>
  2. <button type="button" id="btnAdd">添加style节点</button>
  3. </div>
  4. <div class="div">文本</div>
  5. <script>
  6. document.getElementById("btnAdd").addEventListener("click", createStyleNode)
  7. function createStyleNode() {
  8. const styleNode = document.createElement("style");
  9. // 设置textContent
  10. // styleNode.textContent = `
  11. // .div {
  12. // background-color: red;
  13. // font-size: 30px;
  14. // }
  15. // `;
  16. // append
  17. styleNode.append(`
  18. .div {
  19. background-color: red;
  20. font-size: 30px;
  21. }
  22. `)
  23. document.head.appendChild(styleNode);
  24. }
  25. </script>

操作已有的style节点

这个就得请专业选手 CSS Object Model 入场, 这是一组允许用JavaScript操纵CSS的API。 它是继DOM和HTML API之后,又一个操纵CSS的接口,从而能够动态地读取和修改CSS样式。

先看关系(不包含 layer)

截图_20242120052143.png

现在就做一件事情,把 .div的backgound-color的值从red修改green。从图上可以看到:

  1. CSSStyleSheet也提供了insertRule和deleteRule的方法
  2. StylePropertyMap提供能操作个规则属性的能力。

先看效果:

update_ex.gif

那代码就简单了:

  1. <div>
  2. <button type="button" id="btnUpdate">更改style节点</button>
  3. </div>
  4. <div class="div">文本</div>
  5. <style id="ss-test">
  6. .div {
  7. background-color: red;
  8. font-size: 30px;
  9. }
  10. div {
  11. font-size: 26px
  12. }
  13. </style>
  14. <script>
  15. document.getElementById("btnUpdate").addEventListener("click", updateStyleNode)
  16. function updateStyleNode() {
  17. const styleSheets = Array.from(document.styleSheets);
  18. // ownerNode获得styleSheet对应的节点
  19. const st = styleSheets.find(s=> s.ownerNode.id === "ss-test");
  20. // 选过选择器找到对应的rule
  21. const rule = Array.from(st.cssRules).find(r=> r.selectorText === ".div");
  22. // 兼容性
  23. const styleMap = rule.styleMap;
  24. styleMap.set("background-color", "blue");
  25. }
  26. </script>

操作外部引入样式

动态创建link节点引入样式

我们首先看一下html页面里面通常是怎么引入样式的。

  1. <link rel="stylesheet" href="http://x.com/c.css">

其本质依旧是节点,所以我们可以动态的创建节点,挂载到文档上即可。

  1. function importCSSByUrl(url){
  2. var link = document.createElement('link');
  3. link.type = 'text/css';
  4. link.rel = 'stylesheet';
  5. link.href = url;
  6. document.head.appendChild(link);
  7. }

更改外部引入的样式

那么我们外部引入的CSS,我们也能操作嘛?

答案是肯定的,外面引入的样式最终也会变成一个StyleSheet。 区别在于其href的属性有其全路径, 当然也可以通过 onwerNode的值去识别是link 还是 style方式导入的。

所以,几乎上面的例子,代码只需少量改动。

  1. function updateStyleNode() {
  2. const styleSheets = Array.from(document.styleSheets);
  3. // 通过href判断
  4. const st = styleSheets.find(s => s.href.endsWith("2.3.css"));
  5. const rule = Array.from(st.rules).find(r => r.selectorText === ".div");
  6. const styleMap = rule.styleMap;
  7. styleMap.set("background-color", "green");
  8. }

window.getComputeStyle

功能

Window.getComputedStyle()方法返回一个对象,该对象在应用活动样式表并解析这些值可能包含的任何基本计算后报告元素的所有CSS属性的值。

语法

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

计算后的样式不等同于css和style里面设置的样式

比如font-size属性和transform属性:

效果:

代码:

  1. <div id="div-test" class="div">
  2. 文本
  3. </div>
  4. <hr>
  5. <div>
  6. 样式的值
  7. <pre>
  8. .div {
  9. font-size: 1.6rem;
  10. transform:rotate(3deg);
  11. }
  12. </pre>
  13. </div>
  14. <hr>
  15. <div>
  16. getComputedStyle的值:
  17. <pre id="divGc"></pre>
  18. </div>
  19. <style>
  20. .div {
  21. font-size: 1.6rem;
  22. transform:rotate(3deg);
  23. }
  24. </style>
  25. <script>
  26. const divEl = document.getElementById("div-test");
  27. const styleDeclaration = window.getComputedStyle(divEl);
  28. const fontSize = styleDeclaration.fontSize;
  29. const transform = styleDeclaration.transform;
  30. divGc.textContent = `
  31. fontSize: ${fontSize}
  32. transform: ${transform}
  33. `
  34. </script>

可以获取伪类样式

获取伪类的样式,就得利用第二个参数

  1. const styleDeclaration = window.getComputedStyle(divEl, "before");

效果:

代码:

  1. <div id="div-test" class="div">
  2. 文本
  3. </div>
  4. <hr>
  5. <div>
  6. 伪类的样式:
  7. <pre id="divGc"></pre>
  8. </div>
  9. <style>
  10. .div:before {
  11. content: '(你好)';
  12. font-size: 1.6rem;
  13. }
  14. </style>
  15. <script>
  16. const divEl = document.getElementById("div-test");
  17. const styleDeclaration = window.getComputedStyle(divEl, "before");
  18. const fontSize = styleDeclaration.fontSize;
  19. const content = styleDeclaration.content;
  20. divGc.textContent = `
  21. fontSize: ${fontSize}
  22. content: ${content}
  23. `
  24. </script>

此方法会引起重绘

重排:元素的尺寸、结构、或某些属性发生改变时,浏览器重新渲染部分或全部文档的过程称为重排

重绘: 元素样式的改变并不影响它在文档流中的位置或者尺寸的时候,例如: color, backgound-color, outline-color等,浏览器会重新绘制元素,这个过程称为重绘。

这个在之后可能的加餐中详细说道。

这个是双刃剑。我们通过例子来认知他,动态创建一个create,想让他立马有动画。

下面的代码,没调用 getComputedStyle就不会有动画, 不取值也没有动画

  1. <div>
  2. <button id="btnAdd">动态创建节点并动画</button>
  3. </div>
  4. <div id="container">
  5. </div>
  6. <style>
  7. .ani {
  8. position: absolute;
  9. width: 50px;
  10. height: 50px;
  11. border-radius: 50%;
  12. background-color: blue;
  13. transition: all 3s;
  14. }
  15. </style>
  16. <script>
  17. btnAdd.addEventListener("click", createAni);
  18. function createAni() {
  19. var div = document.createElement('div')
  20. div.className = "ani";
  21. container.appendChild(div);
  22. div.style.left = "0px";
  23. // 去掉这行代码就不会有动画
  24. // window.getComputedStyle(div).height
  25. // window.getComputedStyle(div) 依旧不会有动画
  26. div.style.left = "200px"
  27. }
  28. </script>

我们把样式从内联样式,到style节点(标签),到引入的外部的样式,挨个揍了一遍,一个能打的都没有,还有谁。额,不说了,会的交给你们啦,怎么玩就看你你们啦。

写在最后

不忘初衷,有所得,而不为所累,如果你觉得不错,你的一赞一评就是我前行的最大动力。

微信公众号:成长的程序世界 ,关注之后,海量电子书,打包拿走不送。

或者添加我的微信 dirge-cloud,一起学习。

原文链接:https://www.cnblogs.com/cloud-/p/18091882

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号