Zaznaczanie i manipulowanie pseudoelementami CSS takimi jak: before I: after za pomocą javascript (lub jQuery)

Czy Jest jakiś sposób na zaznaczanie/manipulowanie pseudoelementami CSS, takimi jak ::before i ::after (i stara wersja z jednym dwukropkiem) przy użyciu jQuery?

Na przykład mój arkusz stylów ma następującą regułę:

.span::after{ content:'foo' }

Jak mogę zmienić ' foo 'na' bar ' używając vanilla JS lub jQuery?

Author: Temani Afif, 2011-02-18

22 answers

Możesz również przekazać zawartość do pseudo elementu z atrybutem data, a następnie użyć jQuery do manipulowania tym:

W HTML:

<span>foo</span>

W jQuery:

$('span').hover(function(){
    $(this).attr('data-content','bar');
});

W CSS:

span:after {
    content: attr(data-content) ' any other text you may want';
}

Jeśli chcesz zapobiec pojawieniu się "innego tekstu", możesz połączyć to z rozwiązaniem seucolega w następujący sposób:

W HTML:

<span>foo</span>

W jQuery:

$('span').hover(function(){
    $(this).addClass('change').attr('data-content','bar');
});

W CSS:

span.change:after {
    content: attr(data-content) ' any other text you may want';
}
 725
Author: Nick Kline,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-28 15:11:58

Można by pomyśleć, że byłoby to proste pytanie do odpowiedzi, ze wszystkim innym, co jQuery może zrobić. Niestety problem sprowadza się do problemu technicznego: reguły css: after I: before nie są częścią DOM, i dlatego nie można go zmienić za pomocą metod DOM jQuery.

Istnieją sposoby manipulowania tymi elementami za pomocą obejść JavaScript i/lub CSS; który z nich zależy od twoich dokładnych wymagań.


Zamierzam zacznij od tego, co powszechnie uważane jest za "najlepsze" podejście:

1) Dodaj/usuń określoną klasę

W tym podejściu stworzyłeś już klasę w swoim CSS z innym stylem :after lub :before. Umieść tę" nową " klasę później w arkuszu stylów, aby upewnić się, że nadpisuje:

p:before {
    content: "foo";
}
p.special:before {
    content: "bar";
}

Następnie możesz łatwo dodać lub usunąć tę klasę używając jQuery (lub vanilla JavaScript):

$('p').on('click', function() {
    $(this).toggleClass('special');
});

    $('p').on('click', function() {
      $(this).toggleClass('special');
    });
p:before {
  content: "foo";
  color: red;
  cursor: pointer;
}
p.special:before {
  content: "bar";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
  • plusy: łatwe do implementacja z jQuery; szybko zmienia wiele stylów naraz; wymusza oddzielenie obaw (izolowanie CSS i JS od HTML)
  • wady: CSS musi być wstępnie napisany, więc zawartość :before lub :after nie jest całkowicie dynamiczna

2) Dodawanie nowych stylów bezpośrednio do arkusza stylów dokumentu

Za pomocą JavaScript można dodawać style bezpośrednio do arkusza stylów dokumentu, w tym Style :after i :before. jQuery nie zapewnia wygodny skrót, ale na szczęście JS nie jest aż tak skomplikowany:

var str = "bar";
document.styleSheets[0].addRule('p.special:before','content: "'+str+'";');

var str = "bar";
document.styleSheets[0].addRule('p.special:before', 'content: "' + str + '";');
p:before {
  content: "foo";
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p class="special">This is a paragraph</p>
<p>This is another paragraph</p>

.addRule() i pokrewne metody.insertRule() są dziś dość dobrze wspierane.

Jako wariant, możesz również użyć jQuery, aby dodać zupełnie nowy arkusz stylów do dokumentu, ale wymagany kod nie jest czystszy:

var str = "bar";
$('<style>p.special:before{content:"'+str+'"}</style>').appendTo('head');

var str = "bar";
$('<style>p.special:before{content:"' + str + '"}</style>').appendTo('head');
p:before {
  content: "foo";
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p class="special">This is a paragraph</p>
<p>This is another paragraph</p>

Jeśli mówimy o "manipulowaniu" wartościami, a nie tylko dodawaniu do nich możemy również przeczytaj istniejące style :after lub :before używając innego podejścia:

var str = window.getComputedStyle(document.querySelector('p'), ':before') 
           .getPropertyValue('content');

var str = window.getComputedStyle($('p')[0], ':before').getPropertyValue('content');
console.log(str);

document.styleSheets[0].addRule('p.special:before', 'content: "' + str+str + '";');
p:before {
    content:"foo";
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p class="special">This is a paragraph</p>
<p>This is another paragraph</p>

Możemy zastąpić document.querySelector('p') przez $('p')[0] przy użyciu jQuery, dla nieco krótszego kodu.

  • plusy: każdy łańcuch może być dynamicznie wstawiany do stylu
  • Cons: oryginalne style nie są zmieniane, tylko nadpisywane; wielokrotne użycie (ab)może sprawić, że DOM się rozrośnie dowolnie duże

3) Zmień inny atrybut DOM

Możesz również użyć attr() W CSS, aby odczytać konkretny atrybut DOM. (jeśli przeglądarka obsługuje :before, obsługuje również attr().) łącząc to z content: w jakimś starannie przygotowanym CSS, możemy zmienić treść (ale Nie inne właściwości, jak margines lub kolor) z :before i :after dynamicznie:

p:before {
    content: attr(data-before);
    color: red;
    cursor: pointer;
}

JS:

$('p').on('click', function () {
    $(this).attr('data-before','bar');
});

$('p').on('click', function () {
    $(this).attr('data-before','bar');
});
p:before {
    content: attr(data-before);
    color: red;
    cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
Można to połączyć z drugą techniką, jeśli CSS nie może być przygotowany z wyprzedzeniem:]}
var str = "bar";

document.styleSheets[0].addRule('p:before', 'content: attr(data-before);');

$('p').on('click', function () {
    $(this).attr('data-before', str);
});

var str = "bar";
document.styleSheets[0].addRule('p:before', 'content: attr(data-before) !important;');

$('p').on('click', function() {
  $(this).attr('data-before', str);
});
p:before {
  content: "foo";
  color: red;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
  • plusy: nie tworzy nieskończonych dodatkowych stylów
  • Cons: attr W CSS może mieć zastosowanie tylko do ciągów treści, a nie adresów URL lub kolorów RGB
 496
Author: Blazemonger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-17 13:38:15

Chociaż są one renderowane przez przeglądarki za pomocą CSS tak, jakby były jak inne rzeczywiste elementy DOM, pseudo-elementy same w sobie nie są częścią DOM, ponieważ pseudo-elementy, jak sama nazwa wskazuje, nie są prawdziwymi elementami ,a zatem nie można wybierać i manipulować nimi bezpośrednio za pomocą jQuery (lub żadnych API JavaScript, nawet API selektorów). Dotyczy to wszystkich pseudoelementów, których style próbujesz zmodyfikować za pomocą skryptu, a nie tylko ::before i ::after.

Możesz uzyskać dostęp do stylów pseudoelementów bezpośrednio w czasie wykonywania za pomocą CSSOM (think window.getComputedStyle()), który nie jest ujawniany przez jQuery poza .css(), metodą, która również nie obsługuje pseudoelementów.

Zawsze można znaleźć inne sposoby na obejście tego, na przykład:

  • Stosowanie stylów do pseudoelementów jednej lub więcej dowolnych klas, a następnie przełączanie między klasami (zobacz seucolega ' s answer dla szybkiego przykładu) - jest to idiomatyczny sposób ponieważ używa prostych selektorów (których pseudoelementami nie są) do rozróżniania elementów i stanów elementów, sposób ich użycia

  • Manipulowanie stylami stosowanymi do wspomnianych pseudoelementów, poprzez zmianę arkusza stylów dokumentu, który jest znacznie bardziej hack

 159
Author: BoltClock,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-05 02:37:45

Nie można wybrać pseudo elementów w jQuery, ponieważ nie są one częścią DOM. Ale możesz dodać konkretną klasę do elementu macierzystego i kontrolować jego pseudo elementy w CSS.

Przykład

W jQuery:

<script type="text/javascript">
    $('span').addClass('change');
</script>

W CSS:

span.change:after { content: 'bar' }
 79
Author: Gustavo Sousa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-19 22:13:50

Możemy również polegać na własnych właściwościach (aka zmiennych CSS) w celu manipulowania pseudo-elementem. W specyfikacji możemy przeczytać, że:

Właściwości niestandardowe są zwykłymi właściwościami, więc można je zadeklarować na każdy element, są rozwiązywane z dziedziczeniem normalnym i kaskadą reguły, mogą być warunkowe za pomocą @media i innych reguł warunkowych, mogą być używane w atrybut stylu HTML, mogą być odczytać lub ustawić za pomocą CSSOM , itd.

Biorąc to pod uwagę, ideą jest zdefiniowanie właściwości niestandardowych w elemencie, a pseudo-element po prostu odziedziczy go; w ten sposób możemy go łatwo zmodyfikować.

1) Użycie stylu inline :

.box:before {
  content:var(--content,"I am a before element");
  color:var(--color, red);
  font-size:25px;
}
<div class="box"></div>
<div class="box" style="--color:blue;--content:'I am a blue element'"></div>
<div class="box" style="--color:black"></div>
<div class="box" style="--color:#f0f;--content:'another element'"></div>

2) Korzystanie z CSS i klas

.box:before {
  content:var(--content,"I am a before element");
  color:var(--color, red);
  font-size:25px;
}

.blue {
  --color:blue;
  --content:'I am a blue element';
}
.black {
  --color:black;
}
<div class="box"></div>
<div class="box black" ></div>
<div class="box blue"></div>

3) Korzystanie z javascript

document.querySelectorAll('.box')[0].style.setProperty("--color", "blue");
document.querySelectorAll('.box')[1].style.setProperty("--content", "'I am another element'");
.box:before {
  content:var(--content,"I am a before element");
  color:var(--color, red);
  font-size:25px;
}
<div class="box"></div>
<div class="box"></div>

4) Korzystanie z jQuery

$('.box').eq(0).css("--color", "blue");
/* the css() function with custom properties works only with a jQuery vesion >= 3.x
   with older version we can use style attribute to set the value. Simply pay
   attention if you already have inline style defined! 
*/
$('.box').eq(1).attr("style","--color:#f0f");
.box:before {
  content:"I am a before element";
  color:var(--color, red);
  font-size:25px;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

Może być również używany z wartościami złożonymi:

.box {
  --c:"content";
  --b:linear-gradient(red,blue);
  --s:20px;
  --p:0 15px;
}

.box:before {
  content: var(--c);
  background:var(--b);
  color:#fff;
  font-size: calc(2 * var(--s) + 5px);
  padding:var(--p);
}
<div class="box"></div>

Możesz zauważyć, że rozważam składnię var(--c,value) gdzie value jest wartością domyślną, a także nazywa się wartością awaryjną.

Z tej samej specyfikacji możemy odczytać:

Wartość właściwości niestandardowej może być podstawiona do wartości innej właściwości za pomocą funkcji var (). Składnia var() jest:

var() = var( <custom-property-name> [, <declaration-value> ]? )

Pierwszym argumentem funkcji jest nazwa właściwości niestandardowej, która ma być podstawiona. Drugi argument funkcji, jeśli jest podany, jest wartością zastępczą, która jest używana jako wartość zastępcza , gdy odwołana właściwość niestandardowa jest nieprawidłowa.

I później:

Aby zastąpić var () w wartości właściwości:

  1. jeśli właściwość niestandardowa nazwana przez pierwszą argument do funkcji var() jest splamiony animacją, a funkcja var() jest używana we właściwości animation lub w jednym z jej długich zakresów, traktuj właściwość niestandardową jako posiadającą wartość początkową dla reszty tego algorytmu.
  2. jeśli wartość właściwości niestandardowej nazwanej przez pierwszy argument funkcji var() jest niczym innym niż wartością początkową, zastąp funkcję var() wartością odpowiedniej właściwości niestandardowej.
  3. w przeciwnym razie, Jeśli var() funkcja ma wartość zapasowa jako drugi argument należy zastąpić funkcję var() wartością zapasową. Jeśli istnieją jakieś odniesienia var() w rezerwie, zastąp je również.
  4. W Przeciwnym Razie właściwość zawierająca funkcję var() jest nieprawidłowa w czasie obliczonej wartości.

Jeśli nie ustawimy właściwości niestandardowej lub ustawimy ją na initial lub zawiera ona nieprawidłową wartość, zostanie użyta wartość zapasowa. Użycie initial może być pomocne w przypadku, gdy chcemy zresetować niestandardowe właściwość do jego wartości domyślnej.

Related

Jak zapisać wartość inherit wewnątrz zmiennej CSS (aka właściwość niestandardowa)?

CSS custom properties (variables) for box model

 57
Author: Temani Afif,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-24 12:00:48

W linii tego, co sugeruje Christian, możesz również zrobić:

$('head').append("<style>.span::after{ content:'bar' }</style>");
 37
Author: Ivan Chaer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-18 10:20:22

Oto sposób dostępu do właściwości stylów :after I: before, zdefiniowanych w css:

// Get the color value of .element:before
var color = window.getComputedStyle(
    document.querySelector('.element'), ':before'
).getPropertyValue('color');

// Get the content value of .element:before
var content = window.getComputedStyle(
    document.querySelector('.element'), ':before'
).getPropertyValue('content');
 24
Author: Nedudi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-15 21:55:01

Jeśli chcesz manipulować elementami ::before lub ::after sudo całkowicie za pomocą CSS, możesz to zrobić JS. Patrz poniżej;

jQuery('head').append('<style id="mystyle" type="text/css"> /* your styles here */ </style>');

Zauważ, że element <style> ma ID, którego możesz użyć, aby go usunąć i dodać do niego ponownie, jeśli styl zmieni się dynamicznie.

W ten sposób twój element jest dokładnie taki, jaki chcesz, dzięki CSS, z pomocą JS.

 11
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-14 20:13:28

Jednym z działających, ale niezbyt wydajnych sposobów jest dodanie reguły do dokumentu z nową treścią i odniesienie do niej za pomocą klasy. w zależności od tego, co jest potrzebne, klasa może potrzebować unikalnego identyfikatora dla każdej wartości w treści.

$("<style type='text/css'>span.id-after:after{content:bar;}</style>").appendTo($("head"));
$('span').addClass('id-after');
 5
Author: Christian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-12 13:27:47

Oto HTML:

<div class="icon">
  <span class="play">
    ::before
  </span>
</div>

Obliczony Styl Na 'before' był content: "VERIFY TO WATCH";

Oto moje dwie linie jQuery, które wykorzystują pomysł dodania dodatkowej klasy, aby konkretnie odwołać się do tego elementu, a następnie dodać znacznik stylu (z an!important tag) do zmiany CSS wartości zawartości sudo-elementu:

$("span.play:eq(0)").addClass('G');

$('body').append("<style>.G:before{content:'NewText' !important}</style>");

 5
Author: Coyote,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-18 23:27:20

Dziękuję wszystkim! udało mi się zrobić to co chciałem :D http://jsfiddle.net/Tfc9j/42 / tutaj zajrzyj

Chciałem, aby nieprzezroczystość zewnętrznego div była inna niż nieprzezroczystość wewnętrznego div I Ta zmiana za pomocą kliknięcia somwewhere ;) Dzięki!

   $('#ena').on('click', function () {
        $('head').append("<style>#ena:before { opacity:0.3; }</style>");
    });

$('#duop').on('click', function (e) {

        $('head').append("<style>#ena:before { opacity:0.8; }</style>");

     e.stopPropagation(); 
    });

#ena{
    width:300px;
    height:300px;
    border:1px black solid;
    position:relative;
}
#duo{
    opacity:1;
    position:absolute;
    top:50px;
  width:300px;
    height:100px;
      background-color:white;
}
#ena:before {
    content: attr(data-before);
    color: white;
    cursor: pointer;
    position: absolute;
    background-color:red;
    opacity:0.9;
    width:100%;
    height:100%;
}


<div id="ena">
    <div id="duo">
        <p>ena p</p>
        <p id="duop">duoyyyyyyyyyyyyyy p</p>

    </div>   


</div>
 5
Author: aimiliano,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-10 15:26:38

Możesz utworzyć fałszywą właściwość lub użyć istniejącej właściwości i dziedziczyć ją w arkuszu stylów pseudo-elementu.

var switched = false;

// Enable color switching
setInterval(function () {
    var color = switched ? 'red' : 'darkred';
    var element = document.getElementById('arrow');
    element.style.backgroundColor = color;
    
    // Managing pseudo-element's css
    // using inheritance.
    element.style.borderLeftColor = color;
    
    switched = !switched;
}, 1000);
.arrow {
    /* SET FICTIONAL PROPERTY */
    border-left-color:red;
    
    background-color:red;
    width:1em;
    height:1em;
    display:inline-block;
    position:relative;
}
.arrow:after {
    border-top:1em solid transparent;
    border-right:1em solid transparent;
    border-bottom:1em solid transparent;
    border-left:1em solid transparent;
    
    /* INHERIT PROPERTY */
    border-left-color:inherit;
    
    content:"";
    width:0;
    height:0;
    position:absolute;
    left:100%;
    top:-50%;
}
<span id="arrow" class="arrow"></span>

Wygląda na to, że nie działa dla właściwości "content": (

 4
Author: Alexander Shutau,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-13 13:57:21

To nie jest praktyczne, ponieważ nie napisałem tego do rzeczywistych zastosowań, po prostu dać przykład tego, co można osiągnąć.

css = {
before: function(elem,attr){ 

if($("#cust_style") !== undefined){ 
$("body").append("<style> " + elem + ":before {"  + attr +  "} </style>"); 
} else {
 $("#cust_style").remove();
$("body").append("<style> " + elem + ":before {"  + attr +  "} </style>"); 
}

}, after: function(elem,attr){
if($("#cust_style") !== undefined){ 
$("body").append("<style> " + elem + ":after {"  + attr +  "} </style>"); 

} else { $("#cust_style").remove();
$("body").append("<style> " + elem + ":after {"  + attr +  "} </style>"); 
}
}
}

To obecnie add ' s a / lub dodaje element stylu, który zawiera niezbędne atrybuty, które będą wpływać na element docelowy po Pseudo elemencie.

To może być używane jako

css.after("someElement"," content: 'Test'; position: 'absolute'; ") // editing / adding styles to :after

I

css.before( ... ); // to affect the before pseudo element.

Jak after: I before: pseudo elementy nie są bezpośrednio dostępne przez DOM nie jest obecnie możliwe edytowanie specyficzne wartości css swobodnie.

Mój sposób był tylko przykładem i nie jest dobry do praktyki, można go zmodyfikować wypróbować kilka własnych sztuczek i zrobić to poprawne do użytku w świecie rzeczywistym.

Więc zrób własne eksperymenty z tym i innymi! Pozdrawiam-Adarsh Hegde.
 4
Author: Adarsh Hegde,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-20 11:59:54

Zawsze dodaję własną funkcję utils, która wygląda tak.

function setPseudoElContent(selector, value) {    
    document.styleSheets[0].addRule(selector, 'content: "' + value + '";');
}

setPseudoElContent('.class::after', 'Hello World!');

Lub skorzystaj z funkcji ES6:

const setPseudoElContent = (selector, value) => {    
    document.styleSheets[0].addRule(selector, `content: "${value}";`);
}

setPseudoElContent('.class::after', 'Hello World!');
 4
Author: Orlandster,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-13 09:56:03

Po co dodawać klasy lub atrybuty, skoro można po prostu dodać style do head

$('head').append('<style>.span:after{ content:'changed content' }</style>')
 2
Author: Gaurav Aggarwal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-09 06:10:58

Jest tu wiele odpowiedzi, ale żadna odpowiedź nie pomaga manipulować css :before lub :after, nawet tej zaakceptowanej.

Oto, jak proponuję to zrobić. Załóżmy, że Twój HTML jest taki:

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

A następnie ustawiasz its: before w CSS i projektujesz go tak:

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

Proszę zauważyć, że ustawiłem również content atrybut w samym elemencie, abyś mógł go łatwo później wyjąć. Teraz jest button kliknięcie na które, chcesz zmienić kolor: before na / colspan = " 5 "style =" background: # f6f6f6;" / Można to osiągnąć w następujący sposób:

Zdefiniuj css z wymaganym stylem na jakiejś klasie .activeS:

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

Teraz możesz zmienić styl :before dodając klasę do elementu: before w następujący sposób:

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

Jeśli chcesz tylko uzyskać zawartość :before, można to zrobić jako:

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

Ostatecznie, jeśli chcesz dynamicznie zmieniać zawartość :before przez jQuery, możesz to osiągnąć w następujący sposób:

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

Kliknięcie powyżej przycisk" changeBefore " zmieni :before zawartość #something na '22', która jest wartością dynamiczną.

mam nadzieję, że to pomoże

 2
Author: Learner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-14 13:52:26

Możesz użyć mojej wtyczki do tego celu.

JQuery:

(function() {
  $.pseudoElements = {
    length: 0
  };

  var setPseudoElement = function(parameters) {
    if (typeof parameters.argument === 'object' || (parameters.argument !== undefined && parameters.property !== undefined)) {
      for (var element of parameters.elements.get()) {
        if (!element.pseudoElements) element.pseudoElements = {
          styleSheet: null,
          before: {
            index: null,
            properties: null
          },
          after: {
            index: null,
            properties: null
          },
          id: null
        };

        var selector = (function() {
          if (element.pseudoElements.id !== null) {
            if (Number(element.getAttribute('data-pe--id')) !== element.pseudoElements.id) element.setAttribute('data-pe--id', element.pseudoElements.id);
            return '[data-pe--id="' + element.pseudoElements.id + '"]::' + parameters.pseudoElement;
          } else {
            var id = $.pseudoElements.length;
            $.pseudoElements.length++

              element.pseudoElements.id = id;
            element.setAttribute('data-pe--id', id);

            return '[data-pe--id="' + id + '"]::' + parameters.pseudoElement;
          };
        })();

        if (!element.pseudoElements.styleSheet) {
          if (document.styleSheets[0]) {
            element.pseudoElements.styleSheet = document.styleSheets[0];
          } else {
            var styleSheet = document.createElement('style');

            document.head.appendChild(styleSheet);
            element.pseudoElements.styleSheet = styleSheet.sheet;
          };
        };

        if (element.pseudoElements[parameters.pseudoElement].properties && element.pseudoElements[parameters.pseudoElement].index) {
          element.pseudoElements.styleSheet.deleteRule(element.pseudoElements[parameters.pseudoElement].index);
        };

        if (typeof parameters.argument === 'object') {
          parameters.argument = $.extend({}, parameters.argument);

          if (!element.pseudoElements[parameters.pseudoElement].properties && !element.pseudoElements[parameters.pseudoElement].index) {
            var newIndex = element.pseudoElements.styleSheet.rules.length || element.pseudoElements.styleSheet.cssRules.length || element.pseudoElements.styleSheet.length;

            element.pseudoElements[parameters.pseudoElement].index = newIndex;
            element.pseudoElements[parameters.pseudoElement].properties = parameters.argument;
          };

          var properties = '';

          for (var property in parameters.argument) {
            if (typeof parameters.argument[property] === 'function')
              element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property]();
            else
              element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property];
          };

          for (var property in element.pseudoElements[parameters.pseudoElement].properties) {
            properties += property + ': ' + element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';
          };

          element.pseudoElements.styleSheet.addRule(selector, properties, element.pseudoElements[parameters.pseudoElement].index);
        } else if (parameters.argument !== undefined && parameters.property !== undefined) {
          if (!element.pseudoElements[parameters.pseudoElement].properties && !element.pseudoElements[parameters.pseudoElement].index) {
            var newIndex = element.pseudoElements.styleSheet.rules.length || element.pseudoElements.styleSheet.cssRules.length || element.pseudoElements.styleSheet.length;

            element.pseudoElements[parameters.pseudoElement].index = newIndex;
            element.pseudoElements[parameters.pseudoElement].properties = {};
          };

          if (typeof parameters.property === 'function')
            element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property();
          else
            element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property;

          var properties = '';

          for (var property in element.pseudoElements[parameters.pseudoElement].properties) {
            properties += property + ': ' + element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';
          };

          element.pseudoElements.styleSheet.addRule(selector, properties, element.pseudoElements[parameters.pseudoElement].index);
        };
      };

      return $(parameters.elements);
    } else if (parameters.argument !== undefined && parameters.property === undefined) {
      var element = $(parameters.elements).get(0);

      var windowStyle = window.getComputedStyle(
        element, '::' + parameters.pseudoElement
      ).getPropertyValue(parameters.argument);

      if (element.pseudoElements) {
        return $(parameters.elements).get(0).pseudoElements[parameters.pseudoElement].properties[parameters.argument] || windowStyle;
      } else {
        return windowStyle || null;
      };
    } else {
      console.error('Invalid values!');
      return false;
    };
  };

  $.fn.cssBefore = function(argument, property) {
    return setPseudoElement({
      elements: this,
      pseudoElement: 'before',
      argument: argument,
      property: property
    });
  };
  $.fn.cssAfter = function(argument, property) {
    return setPseudoElement({
      elements: this,
      pseudoElement: 'after',
      argument: argument,
      property: property
    });
  };
})();

$(function() {
  $('.element').cssBefore('content', '"New before!"');
});
.element {
  width: 480px;
  margin: 0 auto;
  border: 2px solid red;
}

.element::before {
  content: 'Old before!';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div class="element"></div>

Wartości powinny być określone, tak jak w normalnej funkcji jQuery.css

Dodatkowo, można również uzyskać wartość parametru pseudo-elementu, jak w normalnej funkcji jQuery.css:

console.log( $(element).cssBefore(parameter) );

JS:

(function() {
  document.pseudoElements = {
    length: 0
  };

  var setPseudoElement = function(parameters) {
    if (typeof parameters.argument === 'object' || (parameters.argument !== undefined && parameters.property !== undefined)) {
      if (!parameters.element.pseudoElements) parameters.element.pseudoElements = {
        styleSheet: null,
        before: {
          index: null,
          properties: null
        },
        after: {
          index: null,
          properties: null
        },
        id: null
      };

      var selector = (function() {
        if (parameters.element.pseudoElements.id !== null) {
          if (Number(parameters.element.getAttribute('data-pe--id')) !== parameters.element.pseudoElements.id) parameters.element.setAttribute('data-pe--id', parameters.element.pseudoElements.id);
          return '[data-pe--id="' + parameters.element.pseudoElements.id + '"]::' + parameters.pseudoElement;
        } else {
          var id = document.pseudoElements.length;
          document.pseudoElements.length++

            parameters.element.pseudoElements.id = id;
          parameters.element.setAttribute('data-pe--id', id);

          return '[data-pe--id="' + id + '"]::' + parameters.pseudoElement;
        };
      })();

      if (!parameters.element.pseudoElements.styleSheet) {
        if (document.styleSheets[0]) {
          parameters.element.pseudoElements.styleSheet = document.styleSheets[0];
        } else {
          var styleSheet = document.createElement('style');

          document.head.appendChild(styleSheet);
          parameters.element.pseudoElements.styleSheet = styleSheet.sheet;
        };
      };

      if (parameters.element.pseudoElements[parameters.pseudoElement].properties && parameters.element.pseudoElements[parameters.pseudoElement].index) {
        parameters.element.pseudoElements.styleSheet.deleteRule(parameters.element.pseudoElements[parameters.pseudoElement].index);
      };

      if (typeof parameters.argument === 'object') {
        parameters.argument = (function() {
          var cloneObject = typeof parameters.argument.pop === 'function' ? [] : {};

          for (var property in parameters.argument) {
            cloneObject[property] = parameters.argument[property];
          };

          return cloneObject;
        })();

        if (!parameters.element.pseudoElements[parameters.pseudoElement].properties && !parameters.element.pseudoElements[parameters.pseudoElement].index) {
          var newIndex = parameters.element.pseudoElements.styleSheet.rules.length || parameters.element.pseudoElements.styleSheet.cssRules.length || parameters.element.pseudoElements.styleSheet.length;

          parameters.element.pseudoElements[parameters.pseudoElement].index = newIndex;
          parameters.element.pseudoElements[parameters.pseudoElement].properties = parameters.argument;
        };

        var properties = '';

        for (var property in parameters.argument) {
          if (typeof parameters.argument[property] === 'function')
            parameters.element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property]();
          else
            parameters.element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property];
        };

        for (var property in parameters.element.pseudoElements[parameters.pseudoElement].properties) {
          properties += property + ': ' + parameters.element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';
        };

        parameters.element.pseudoElements.styleSheet.addRule(selector, properties, parameters.element.pseudoElements[parameters.pseudoElement].index);
      } else if (parameters.argument !== undefined && parameters.property !== undefined) {
        if (!parameters.element.pseudoElements[parameters.pseudoElement].properties && !parameters.element.pseudoElements[parameters.pseudoElement].index) {
          var newIndex = parameters.element.pseudoElements.styleSheet.rules.length || parameters.element.pseudoElements.styleSheet.cssRules.length || parameters.element.pseudoElements.styleSheet.length;

          parameters.element.pseudoElements[parameters.pseudoElement].index = newIndex;
          parameters.element.pseudoElements[parameters.pseudoElement].properties = {};
        };

        if (typeof parameters.property === 'function')
          parameters.element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property();
        else
          parameters.element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property;

        var properties = '';

        for (var property in parameters.element.pseudoElements[parameters.pseudoElement].properties) {
          properties += property + ': ' + parameters.element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';
        };

        parameters.element.pseudoElements.styleSheet.addRule(selector, properties, parameters.element.pseudoElements[parameters.pseudoElement].index);
      };
    } else if (parameters.argument !== undefined && parameters.property === undefined) {
      var windowStyle = window.getComputedStyle(
        parameters.element, '::' + parameters.pseudoElement
      ).getPropertyValue(parameters.argument);

      if (parameters.element.pseudoElements) {
        return parameters.element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] || windowStyle;
      } else {
        return windowStyle || null;
      };
    } else {
      console.error('Invalid values!');
      return false;
    };
  };

  Object.defineProperty(Element.prototype, 'styleBefore', {
    enumerable: false,
    value: function(argument, property) {
      return setPseudoElement({
        element: this,
        pseudoElement: 'before',
        argument: argument,
        property: property
      });
    }
  });
  Object.defineProperty(Element.prototype, 'styleAfter', {
    enumerable: false,
    value: function(argument, property) {
      return setPseudoElement({
        element: this,
        pseudoElement: 'after',
        argument: argument,
        property: property
      });
    }
  });
})();

document.querySelector('.element').styleBefore('content', '"New before!"');
.element {
  width: 480px;
  margin: 0 auto;
  border: 2px solid red;
}

.element::before {
  content: 'Old before!';
}
<div class="element"></div>

GitHub: https://github.com/yuri-spivak/managing-the-properties-of-pseudo-elements/

 1
Author: Yuri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-05 11:48:01

Użyłem zmiennych zdefiniowanych w :root wewnątrz CSS, Aby zmodyfikować :after (to samo dotyczy :before) pseudoelement , w szczególności do zmiany wartości background-color dla stylizowanego anchor zdefiniowanego przez .sliding-middle-out:hover:after i wartości content dla innego anchor (#reference) W poniższym demo , które generuje losowe kolory za pomocą JavaScript / jQuery:

HTML

<a href="#" id="changeColor" class="sliding-middle-out" title="Generate a random color">Change link color</a>
<span id="log"></span>
<h6>
  <a href="https://stackoverflow.com/a/52360188/2149425" id="reference" class="sliding-middle-out" target="_blank" title="Stack Overflow topic">Reference</a>
</h6>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/davidmerfield/randomColor/master/randomColor.js"></script>

CSS

:root {
    --anchorsFg: #0DAFA4;
}
a, a:visited, a:focus, a:active {
    text-decoration: none;
    color: var(--anchorsFg);
    outline: 0;
    font-style: italic;

    -webkit-transition: color 250ms ease-in-out;
    -moz-transition: color 250ms ease-in-out;
    -ms-transition: color 250ms ease-in-out;
    -o-transition: color 250ms ease-in-out;
    transition: color 250ms ease-in-out;
}
.sliding-middle-out {
    display: inline-block;
    position: relative;
    padding-bottom: 1px;
}
.sliding-middle-out:after {
    content: '';
    display: block;
    margin: auto;
    height: 1px;
    width: 0px;
    background-color: transparent;

    -webkit-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
    -moz-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
    -ms-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
    -o-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
    transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
}
.sliding-middle-out:hover:after {
    width: 100%;
    background-color: var(--anchorsFg);
    outline: 0;
}
#reference {
  margin-top: 20px;
}
.sliding-middle-out:before {
  content: attr(data-content);
  display: attr(data-display);
}

JS / jQuery

var anchorsFg = randomColor();
$( ".sliding-middle-out" ).hover(function(){
    $( ":root" ).css({"--anchorsFg" : anchorsFg});
});

$( "#reference" ).hover(
 function(){
    $(this).attr("data-content", "Hello World!").attr("data-display", "block").html("");
 },
 function(){
    $(this).attr("data-content", "Reference").attr("data-display", "inline").html("");
 }
);
 1
Author: Riccardo Volpe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-17 16:19:24

Stworzyłem wtyczkę jQuery do dodawania css-pseudo reguł, takich jak używanie .css() dla określonych elementów.

  • kod wtyczki i przypadek testowy to tutaj
  • użyj przypadku jako prostego css image popup tutaj

Użycie:

$('body')
  .css({
    backgroundColor: 'white'
  })
  .cssPseudo('after', {
    content: 'attr(title) ", you should try to hover the picture, then click it."',
    position: 'absolute',
    top: 20, left: 20  
  })
  .cssPseudo('hover:after', {
    content: '"Now hover the picture, then click it!"'
  });

 1
Author: BananaAcid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-02-03 06:55:17

 $('.span').attr('data-txt', 'foo');
        $('.span').click(function () {
         $(this).attr('data-txt',"any other text");
        })
.span{
}
.span:after{ 
  content: attr(data-txt);
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='span'></div>
 0
Author: Tariq Javed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-28 11:42:19

Ktoś inny skomentował dodawanie do elementu head pełnego elementu stylu i nie jest to złe, jeśli robisz to tylko raz, ale jeśli chcesz go zresetować więcej niż raz, skończysz z mnóstwem elementów stylu. Tak więc, aby zapobiec stworzeniu pustego elementu stylu w głowie z id i zastąpić go innerHTML w ten sposób:

<style id="pseudo"></style>

Wtedy JavaScript wyglądałby tak:

var pseudo = document.getElementById("pseudo");

function setHeight() {
    let height = document.getElementById("container").clientHeight;
    pseudo.innerHTML = `.class:before { height: ${height}px; }`
}

setHeight()

Teraz w moim przypadku potrzebowałem tego, aby ustawić wysokość elementu before na podstawie wysokość innego i zmieni się przy zmianie rozmiaru, więc za pomocą tego mogę uruchomić setHeight() za każdym razem, gdy okno zostanie zmienione i zastąpi <style> poprawnie.

mam nadzieję, że to pomoże komuś, kto utknął próbując zrobić to samo.

 0
Author: zfb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-22 11:01:51

Mam dla Ciebie coś innego, co jest łatwe i skuteczne.

    <style> 
    .case-after:after { // set your properties here like eg: 
        color:#3fd309 !important; 
     } 
     .case-before:before { // set your properties here like eg: 
        color:#151715 !important; 
     }
 </style>
  // case for after
    $('#button-id').on('click', function() {
        $(".target-div").toggleClass('case-after');
    });

     // case for before
    $('#button-id').on('click', function() {
        $(".target-div").toggleClass('case-before');
    });
 -1
Author: Coding_snakeZ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-11-12 09:32:18