首頁 >web前端 >js教程 >如何使用 JavaScript/jQuery 選擇和操作 CSS 偽元素(::before、::after)?

如何使用 JavaScript/jQuery 選擇和操作 CSS 偽元素(::before、::after)?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-12-21 08:37:10771瀏覽

How Can I Select and Manipulate CSS Pseudo-elements (::before, ::after) with JavaScript/jQuery?

使用JavaScript/jQuery 選擇和操作CSS 偽元素

使用JavaScript 或jQuery 選擇和操作::before 和::after 等CSS 偽元素,您可以採用幾種不同的技術。

使用操作內容jQuery

jQuery 允許您擷取和操作偽元素的內容,如下所示:

// Get the content of ::after for an element with class "span"
var content = $('.span::after').text();

要更改內容,只需分配一個新值:

// Change the content of ::after for elements with class "span"
$('.span::after').text('bar');

用資料操作內容屬性

或者,您可以使用資料屬性和 jQuery將內容傳遞給偽元素:

<!-- Element with a data attribute -->
<span data-content="foo">foo</span>
// Get the content from the data attribute
var content = $('span').attr('data-content');

// Manipulate the pseudo-element content
$('.span::after').text(content);

要更改懸停時的內容,您可以結合使用此方法使用事件處理程序:

$('span').hover(function() {
  // Change the content of ::after on hover
  $(this).attr('data-content', 'bar');
});
span::after {
  content: attr(data-content) /* Combine this with seucolega's solution */ ' any other text you may want';
}

透過使用這些技術,您可以動態控制內容以及Web 應用程式中偽元素的出現。

以上是如何使用 JavaScript/jQuery 選擇和操作 CSS 偽元素(::before、::after)?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn