DOM外联样式相关操作
DOM外联样式相关操作
DOM在对css样式进行修改的时候,直接使用style会出现无法获取外联样式表样式的情况,这时需要使用CSS 样式声明对象(CSSStyleDeclaration),其中有一个cssText属性,用于设置或返回样式声明文本,cssText 对应的是 HTML 元素的 style 属性。
语法如下:
返回 cssText 属性:
element.style.cssText
设置 cssText 属性:
element.style.cssText = style
设置指定元素的内联样式:
document.getElementById("ex1").style.cssText = "color: blue;";
获取外联样式:
let child1 = document.getElementById("div2");
let style1 = window.getComputedStyle(child1);
详细案例如下:(vue文件)
<template>
<div class="rainRound" id="div1" style>
<div class="yudi" id="div2" style="margin-left:120px"></div>
</div>
</template>
<script>
export default {
name: "testVue",
data() {
return {
//
};
},
mounted() {
let el = document.createElement("div");
let child1 = document.getElementById("div2");
let style2 = window.getComputedStyle(child1);
let style1 = child1.style;
el.style.cssText = style2.cssText;
let style3 = el.style;
let leftA = Math.floor(Math.random() * 1660 + 2);
el.style.marginLeft = leftA + "px";
let par = document.getElementById("div1");
par.appendChild(el);
// for (let i = 0; i < 100; i++) {
//let par = document.getElementById("div1");
//for (let i = 0; i < 30; i++) {
// let clone1 = child1.cloneNode(true);
// let leftA = Math.floor(Math.random() * 1660 + 2);
// clone1.style.marginLeft = leftA + "px";
// let sec = Math.floor(Math.random() * 10 + 1);
// clone1.style.animationDelay = sec + "s";
// par.appendChild(clone1);
//}
//let el = document.createElement("div");
//el.style = style1;
//let classA = document.createAttribute("class");
//classA.nodeValue = "yudi";
//el.attributes.setNamedItem(classA);
//el.style.marginLeft = leftA + "px";
//par.appendChild(el);
//},
//methods: {
//
},
};
</script>
<style lang="scss" scoped>
.rainRound {
position: relative;
height: 100%;
background-color: rgb(150, 187, 179);
.yudi {
position: relative;
width: 4px;
height: 6px;
background-color: aqua;
clip-path: ellipse(10% 30% at 50% 50%);
transform: scale(6);
animation: roundRain 1s ease-in infinite;
}
}
@keyframes roundRain {
0% {
opacity: 0;
}
20% {
opacity: 1;
}
90% {
opacity: 1;
}
100% {
opacity: 0;
transform: translate3d(10px, 700px, -10px);
}
}
</style>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律