使用自定义字段操作伪元素

Manipulate Pseudo Elements with Custom Fields

我需要做的与此类似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>

我无法理解关于 自定义字段 的部分,但是如果您打算无限控制 pseudo-elements,那么祝您好运。目前,用Javascript操纵pseudo-elements可以通过将内联css注入DOM,如this post中所述,但是不推荐,当然,除非你绝对必须这样做。

因此,另一种更改 pseudo-elements 的方法是在元素上更改 add/remove/modify class 名称。请参阅下面的示例代码和 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中的classes,并根据用户交互将它们切换为Javascript。就是这样。