笔记三十九:jquery动态修改:after:before伪元素content值

252 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>jquery动态修改伪类:after:before</title>
    	<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
		<style>
			*{
				padding: 0;
				margin: 0;
			}
			body{
				padding: 0;
				margin: 0;
			}
			#box{
				width: 200px;
			    height: 200px;
			    position: fixed;
			    top: calc(50% - 100px);
			    left: calc(50% - 100px);
			    background: #0877FF;
			    border-radius: 10px;
			    text-align: center;
			    box-shadow: 1px 2px 3px -1px;
			}
			#box:after{
				content: attr(data-content-after);
			    position: relative;
			    top: -120px;
			    left: -160px;
			    width: 104px;
			    height: 100px;
			    line-height: 100px;
			    text-align: center;
			    border-radius: 10px;
			    background: orange;
			    box-shadow: 1px 2px 3px -1px;
			    display: block;
			}
			#box:before{
				content: attr(data-content-before);
			    position: relative;
			    top: 0;
			    right: -260px;
			    width: 104px;
			    height: 100px;
			    line-height: 100px;
			    text-align: center;
			    border-radius: 10px;
			    background: #39c778;
			    box-shadow: 1px 2px 3px -1px;
			    display: block;
			}
		</style>
	</head>
	<body>
		<div id="box" data-content-before=":before" data-content-after=":after">box盒子</div>
		
		<script type="text/javascript">
			//jquery直接用attr方法替换,简单粗暴;
			$('#box').attr("data-content-before",':before伪元素');
			$('#box').attr("data-content-after",':after伪元素');
		</script>
	</body>
</html>