如何通过 Javascript 更改伪 :before 元素的内容值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10495243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:36:28  来源:igfitidea点击:

How change content value of pseudo :before element by Javascript

javascriptjquery

提问by jumancy

I have the grap constructured by CSS, which is dynamically changes by JS. I show graph max value by pseudo element as:

我有由 CSS 构造的 grap,它是由 JS 动态更改的。我通过伪元素显示图形最大值为:

.graph:before {
    content:""; //value that want set by JS
    position:absolute;
    top:0;
    left:0;
}

That's why I need to set this value by JS. I tried $(".graph:before").css("content", hh);but it didn't help. How to get that value?

这就是为什么我需要通过 JS 设置这个值。我试过了,$(".graph:before").css("content", hh);但没有帮助。如何获得那个值?

采纳答案by James Allardice

Update (2018): as has been noted in the comments, you now cando this.

更新(2018 年):正如评论中所述,您现在可以执行此操作。

You can't modify pseudo elements through JavaScript since they are not part of the DOM. Your best bet is to define another class in your CSS with the styles you require and then add that to the element. Since that doesn't seem to be possible from your question, perhaps you need to look at using a real DOM element instead of a pseudo one.

您不能通过 JavaScript 修改伪元素,因为它们不是 DOM 的一部分。最好的办法是在 CSS 中定义另一个具有所需样式的类,然后将其添加到元素中。由于您的问题似乎不可能,因此您可能需要考虑使用真正的 DOM 元素而不是伪元素。

回答by Santosh D

I hope the below snippet might help, you can specify the contentvalue you want via JS using the CSS attr()function. Below you have two options: to use JavaScript or jQuery:

我希望下面的代码片段可能会有所帮助,您可以content使用 CSSattr()函数通过 JS指定您想要的值。下面有两个选项:使用 JavaScript 或 jQuery:

jQuery:

jQuery:

$('.graph').on('click', function () {
    //do something with the callback
    $(this).attr('data-before','anything'); //anything is the 'content' value
});

JavaScript:

JavaScript:

var graphElem = document.querySelector('.graph');
graphElem.addEventListener('click', function (event) {
    event.target.setAttribute('data-before', 'anything');
});

CSS:

CSS:

.graph:before {
    content: attr(data-before); /* value that that refers to CSS 'content' */
    position:absolute;
    top: 0;
    left: 0;
}

回答by Gennadiy Gorbulin

You can use CSS variable

您可以使用 CSS 变量

:root {
  --h: 100px;
}

.elem:after {
  top: var(--h);
}

let y = 10;

document.documentElement.style.setProperty('--h', y + 'px')

https://codepen.io/Gorbulin/pen/odVQVL

https://codepen.io/Gorbulin/pen/odVQVL

回答by Learner

People who are still looking some solution of same problem, it is doable as follows using jQuery:

仍在寻找相同问题的一些解决方案的人,使用 jQuery 如下所示:

<button id="changeBefore">Change</button>
<script>
    var newValue = '22';//coming from somewhere
    var add = '<style>.graph:before{content:"'+newValue+'"!important;}</style>';
    $('#changeBefore').click(function(){
        $('body').append(add);
    });
</script>

This example illustrate that on clicking button: changeBefore, the value for .graph:beforewill change as per new dynamic coming value for it.

此示例说明单击 button: 时changeBefore,其值.graph:before将根据新的动态即将到来的值而变化。

For more description about changing of :beforeor :afterelement style or getting its content:

有关更改:before:after元素样式或获取其内容的更多说明:

Lets suppose your HTML is like this:

假设你的 HTML 是这样的:

<div id="something">Test</div>

And then you are setting its :before in CSS and designing it like:

然后您在 CSS 中设置它的 :before 并将其设计为:

#something:before{
   content:"1st";
   font-size:20px;
   color:red;
}
#something{
  content:'1st';
}

Please notice I also set contentattribute in element itself so that you can take it out easily later. Now there is a buttonclicking on which, you want to change the color of :before to green and its font-size to 30px. You can achieve that as follows:

请注意,我还在content元素本身中设置了属性,以便您以后可以轻松地将其取出。现在有一个button点击,您想将 :before 的颜色更改为绿色,并将其字体大小更改为 30px。您可以通过以下方式实现:

Define a css with your required style on some class .activeS:

在某些类上定义具有所需样式的 css .activeS

.activeS:before{
   color:green !important;
   font-size:30px !important;
 }

Now you can change :before style by adding the class to your :before element as follows:

现在您可以通过将类添加到您的 :before 元素来更改 :before 样式,如下所示:

<button id="changeBefore">Change</button>
<script>
    $('#changeBefore').click(function(){
        $('#something').addClass('activeS');
    });
</script>

If you just want to get content of :before, it can be done as:

如果您只想获取 的内容:before,可以这样做:

<button id="getContent">Get Content</button>
<script>
    $('#getContent').click(function(){
        console.log($('#something').css('content'));//will print '1st'
    });
</script>

I hope it helps

我希望它有帮助

回答by FrancoSF

I believe there is a simple solution using the attr() function to specify the content of the pseudo element. Here is a working example using the 'title' attribute, but it should work also with custom attributes.:

我相信有一个简单的解决方案,使用 attr() 函数来指定伪元素的内容。这是一个使用“title”属性的工作示例,但它也适用于自定义属性。:

document.getElementById('btn_change1').addEventListener("click", function(){
    document.getElementById('test_div').title='Status 1';
});
   
document.getElementById('btn_change2').addEventListener("click", function(){       
    document.getElementById('test_div').title='Status 2';
});
#test_div {
   margin: 4em;
   padding:2em;
   background: blue;
   color: yellow;
}

#test_div:after {
   content:attr(title);
   background: red;
   padding:1em;
}
<button id='btn_change1'>Change div:after to [Status 1]</button>
<button id='btn_change2'>Change div:after to [Status 2]</button>

<div id='test_div' title='Initial Status'>The element to modify</div>

回答by Anandaweb

I had a similar problem, but with icons. I needed to switch the play and pause icons for an audio player in html5.

我有一个类似的问题,但有图标。我需要在 html5 中切换音频播放器的播放和暂停图标。

The problem here was that HTML, CSS and jQuery all interpret differently the "content" values to show icons, due to the use of \ symbol.

这里的问题是,由于使用了 \ 符号,HTML、CSS 和 jQuery 都以不同的方式解释“内容”值以显示图标。

So the best workaround is to delete and re-create the node. Here's my code:

所以最好的解决方法是删除并重新创建节点。这是我的代码:

<ul class="list list--buttons">
    <li><a href="#" class="list__link previuos"><i class="fa fa-step-backward"></i></a></li>

    <li><a href="#" class="list__link playpause"><i class="fa fa-play"></i></a></li>

    <li><a href="#" class="list__link next"><i class="fa fa-step-forward"></i></a></li>
</ul>

And the script

还有剧本

<script type="text/javascript">
            $(
                function(){
                    var aud = $('audio')[0];
                    $('.playpause').on('click', function(e){
                        e.preventDefault();
                    if (aud.paused) {
                        aud.play();
                        /* from play icon to pause icon */
                        $('.playpause .fa-play').remove();
                        $('.playpause').append('<i class="fa fa-pause"></i>');
                    }
                    else {
                        aud.pause();
                        /* from play icon to pause icon */
                        $('.playpause .fa-pause').remove();
                        $('.playpause').append('<i class="fa fa-play"></i>');
                    }

                })
                $('.next').on('click', function(e){
                    e.preventDefault();
                    aud.src = '{$content:audio-file}';
                })
                $('.previuos').on('click', function(e){
                    e.preventDefault();
                    aud.src = '{$content:audio-file}';
                })
                aud.ontimeupdate = function(){
                    $('.progress').css('width', aud.currentTime / aud.duration * 100 + '%')
                }
            })
        </script>

Hope it helps!

希望能帮助到你!

回答by GerA

If you use something like an onoffswitchand want to translate the css content attribute with i18nextthen you can use one of the i18next Frameworkexample from github(i18next Jquery Framework) and then you extended the function with this code:

如果您使用的东西,像一个onoffswitch和想翻译与CSS内容属性i18next那么你可以使用的一个i18next框架例如从github上(i18next jQuery框架),然后您扩展与此代码的功能:

var before = i18next.t('onoffswitch.before');
var after = i18next.t('onoffswitch.after');
$('.onoffswitch-inner')
    .attr('data-before', before )
    .attr('data-after', after );

and the css code must be this:

并且 css 代码必须是这样的:

.onoffswitch-inner:before {
    content:  attr(data-before);
    padding-left: 10px;
    background-color: #65AFF5; color: #FFFFFF;
}
.onoffswitch-inner:after {
    content:  attr(data-after);
    padding-right: 10px;
    background-color: #EEEEEE; color: #999999;
    text-align: right;
}