使用自定义字段处理伪元素

时间:2016-01-15 16:46:20

标签: javascript css pseudo-element

我需要做的是与此post类似,但我需要用户能够使用自定义字段更改伪元素。仍在学习JavaScript,这一直是一场斗争!

用户需要改变〜border-right的能力:500px solid#4679BD;

自定义字段是〜$ angle = get_field('contact_angle_color');

这是我的代码没有失败的JavaScript尝试:

.relative-wrap {
position: relative;	
min-height: 150px;
}

	.triangle-down-right {
	width: 50%;
	height: 0;
	padding-top: 54%;
	overflow: hidden;
	position: absolute;
	top: 0;
	right: 0;
	}
	
	.triangle-down-right:after {
	content: "";
	display: block;
	width: 0;
	height: 0;
	margin-top:-500px;
	border-top: 500px solid transparent;
	border-right: 500px solid #4679BD;
	}
<div class="triangle-down-right"></div>

1 个答案:

答案 0 :(得分:0)

我无法理解关于自定义字段的部分,但如果您计划对伪元素进行无限制控制,那么,祝你好运。目前,如this post中所述,通过将内联css注入DOM ,可以使用Javascript操作伪元素,但不建议这样做,除非你绝对不得不这样做。

因此,更改伪元素的另一种方法是在元素上添加/删除/修改类名。请参阅下面的示例代码和JSFiddle:https://jsfiddle.net/9w4d6mts/

<强> HTML:

<input type="button" id="direction" value="Change Direction">
<br>
<input type="button" id="color" value="Change Color">
<div id="demo" class="triangle-down-right alt"></div>

<强> CSS:

.relative-wrap {
  position: relative;   
  min-height: 150px;
}

.triangle-down-right,
.triangle-down-left {
    width: 50%;
    height: 0;
    padding-top: 54%;
    overflow: hidden;
    position: absolute;
    top: 0;
    right: 0;
}

.triangle-down-right:after,
.triangle-down-left:after {
    content: "";
    display: block;
    width: 0;
    height: 0;
    margin-top:-500px;
    border-top: 500px solid transparent;
}

.triangle-down-right:after {
  border-right: 500px solid #4679BD;
}

.triangle-down-left:after {
  border-left: 500px solid #4679BD;
}

.triangle-down-right.alt:after,
.triangle-down-left.alt:after {
  border-color: transparent #D4679B transparent;
}

<强> JS:

document.getElementById('direction').addEventListener('click', function(){
    var d = document.getElementById('demo');
  d.className = (d.className.replace(' alt','') === "triangle-down-right") ? d.className.replace('right','left') : d.className.replace('left','right');
});

document.getElementById('color').addEventListener("click", function(){
    var d = document.getElementById('demo');
    console.log(d.className);
    d.className = (d.className.slice(-3) === "alt") ? d.className.replace(' alt','') : d.className + ' alt';
});

基本上,我们预先在CSS中准备类,并根据用户交互使用Javascript切换它们。就是这样。