Linkage of css content with HTML and JavaScript

HTML, CSS, and JavaScript are separated from each other and perform their duties.
This is the basic principle that beginners of front-end development know


In particular, CSS, and JavaScript, both revolve around HTML, but there is little contact between the two.
The relationship between CSS and HTML is that CSS modifies HTML, and almost all CSS unilaterally directs HTML. On the
whole, CSS is "independent." Child"


But there are exceptions to everything. In very rare cases, CSS still has to be controlled by HTML,
such as the content attribute of pseudo-classes.


Many beginners only know that the content of the pseudo-class can be set to a string, but they don't know that it can also be set to an attr() expression, so as to obtain dynamic data
content and splicing text content, using multiple attr() together

css content: attr (attribute name);
corresponding
to the attribute name in HTML = "value obtained by content"
see demo for details

demo

<!DOCTYPE html>
<html>

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<meta charset="utf-8">
	<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
	<title>css content 与 HTML, JavaScript 的联动</title>
	<style>
		.div::before {
     
     
			outline: 1px green solid;
			content: attr(data-before);
		}

		.div::after {
     
     
			outline: 1px green solid;
			content: attr(data-after);
		}

		#div3::after {
     
     
			content: "还可以拼接文本内容, 多 attr() 连用 "attr(data-after)" , "attr(data-before);
		}
	</style>
</head>

<body>

	<div class="div" id="div0" data-before="初始 before" data-after="初始 after"> div </div>
	<div class="div" id="div1" data-before="初始 before" data-after="初始 after"> div </div>
	<div class="div" id="div2" data-before="初始 before" data-after="初始 after"> div </div>
	<div class="div" id="div3" data-before="初始 before" data-after="初始 after"> div </div>

	<script type="text/javascript">
		"use strict"

		window.onload = function () {
     
     
			document.getElementById("div1").setAttribute("data-after", "setAttribute 修改了 after")
			document.getElementById("div2").dataset.before = "dataset 修改了 before"

		}
	</script>
</body>

</html>

Once the CSS value is linked to the attribute value of the HTML element, it is easy to obtain and modify the value with JavaScript

end

Guess you like

Origin blog.csdn.net/u013970232/article/details/110533414