如何通过jQuery修改.para-top:before的left属性值?
.para-top:before Left Property Ah, I feel your pain—trying to adjust the left property of a pseudo-element like .para-top:before with jQuery's attr() method just won't cut it, and it's totally confusing at first. Let's break down why this happens and the proper ways to fix it.
Why attr() Doesn't Work
Pseudo-elements like :before and :after aren't actual DOM elements—they're virtual elements generated by the browser based on your CSS rules. jQuery's attr() method only targets real DOM node attributes, so it can't reach these virtual pseudo-elements at all. That's why your attempts to use it here are failing.
Solution 1: Use CSS Class Switching (Recommended)
This is the cleanest, most maintainable approach. We'll define a new CSS class that overrides the left property of the pseudo-element, then use jQuery to add this class to the target element.
- First, add this to your CSS stylesheet:
/* Define the new style for the pseudo-element */ .para-top.custom-pseudo-left:before { left: 284px; }
- Then, use jQuery to apply the class to
.para-top:
$('.para-top').addClass('custom-pseudo-left');
- If you need to toggle the style later, use
toggleClass('custom-pseudo-left') - To remove it, use
removeClass('custom-pseudo-left')
Solution 2: Dynamically Insert a Style Tag
If you need to set the value dynamically (e.g., based on user input or calculated values), you can create a new <style> element and inject it into the page's <head>.
// Create the style rule and append it to the head $('head').append(` <style> .para-top:before { left: 284px !important; /* Use !important only if needed to override higher-priority styles */ } </style> `);
Note: Only use !important if your original CSS rule has higher specificity and you can't adjust the selector to be more specific.
Final Notes
Stick with the class-based approach whenever possible—it keeps your styles organized and makes it easier to debug later. The dynamic style tag method is great for one-off, dynamic value scenarios.
内容的提问来源于stack exchange,提问作者Sarath

