programing tip

JQuery를 사용하여 : Before CSS 선택기의 너비 속성 변경

itbloger 2020. 11. 26. 07:58
반응형

JQuery를 사용하여 : Before CSS 선택기의 너비 속성 변경


이미지가있는 페이지가 있고 : before CSS 선택기를 사용하여 스타일을 지정했습니다.
이미지는 동적이므로 너비가 고정되어 있지 않습니다. 그래서 나는 규칙의 너비 전에 동적으로 설정해야합니다.
JQuery를 사용하여 클라이언트 측에서하고 싶습니다.
이것을 가정하십시오 :

.column:before{
    width: 300px;
    float: left;
    content: "";
    height: 430px;
}

.column{
    width: 500px;
    float: right;
    padding: 5px;
    overflow: hidden;
    text-align: justify;
}

:beforeJQuery를 사용하여 선택자가없는 클래스의 너비 속성 만 변경할 수있는 방법은 무엇입니까?


의사 클래스의 규칙에 직접 액세스하는 jQuery 방식이 있다고 생각하지 않지만 항상 style다음과 같이 문서의 머리에 요소를 추가 할 수 있습니다 .

$('head').append('<style>.column:before{width:800px !important;}</style>');

여기 에서 라이브 데모 보기

나는 또한이 문제를 한 번 해결하는 플러그인을 본 기억이 있지만 불행히도 처음 인터넷 검색에서 찾을 수 없었습니다.


의사 요소는 Shadow DOM의 일부이며 수정할 수 없습니다 (하지만 값을 쿼리 할 수 있음).

그러나 때로는 클래스를 사용하여이를 해결할 수 있습니다.

jQuery

$('#element').addClass('some-class');

CSS

.some-class:before {
    /* change your properties here */
}

이것은 쿼리에 적합하지 않을 수 있지만 때때로이 패턴을 달성 할 수 있음을 보여줍니다.

의사 요소의 값을 얻으려면 다음과 같은 코드를 시도하십시오.

var pseudoElementContent = window.getComputedStyle($('#element')[0], ':before')
  .getPropertyValue('content')

의사 요소는 DOM의 일부가 아니므로 jQuery 또는 Javascript를 사용하여 조작 할 수 없습니다.

그러나 수락 된 답변에서 지적했듯이 JS를 사용하여 의사 요소 스타일링이 끝나는 스타일 블록을 추가 할 수 있습니다.


대답은 Jain 이어야합니다 . 의사 선택기를 통해 요소를 선택할 수 없지만을 사용하여 스타일 시트에 새 규칙을 추가 할 수 있습니다 insertRule.

나는 당신을 위해 일해야 할 것을 만들었습니다.

var addRule = function(sheet, selector, styles) {
    if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
    if (sheet.addRule) return sheet.addRule(selector, styles);
};

addRule(document.styleSheets[0], "body:before", "content: 'foo'");

http://fiddle.jshell.net/MDyxg/1/

매우 멋지게 (그리고 실제로 질문에 답하기 위해 ) 나는 그것을 다시 롤아웃하고 이것을 jQuery-plugin으로 래핑했습니다 (그러나 jquery는 여전히 필요하지 않습니다!).

/*!
 * jquery.addrule.js 0.0.1 - https://gist.github.com/yckart/5563717/
 * Add css-rules to an existing stylesheet.
 *
 * @see http://stackoverflow.com/a/16507264/1250044
 *
 * Copyright (c) 2013 Yannick Albert (http://yckart.com)
 * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php).
 * 2013/05/12
 **/

(function ($) {

    window.addRule = function (selector, styles, sheet) {

        styles = (function (styles) {
            if (typeof styles === "string") return styles;
            var clone = "";
            for (var p in styles) {
                if (styles.hasOwnProperty(p)) {
                    var val = styles[p];
                    p = p.replace(/([A-Z])/g, "-$1").toLowerCase(); // convert to dash-case
                    clone += p + ":" + (p === "content" ? '"' + val + '"' : val) + "; ";
                }
            }
            return clone;
        }(styles));
        sheet = sheet || document.styleSheets[document.styleSheets.length - 1];

        if (sheet.insertRule) sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
        else if (sheet.addRule) sheet.addRule(selector, styles);

        return this;

    };

    if ($) $.fn.addRule = function (styles, sheet) {
        addRule(this.selector, styles, sheet);
        return this;
    };

}(window.jQuery));

사용법은 매우 간단합니다.

$("body:after").addRule({
    content: "foo",
    color: "red",
    fontSize: "32px"
});

// or without jquery
addRule("body:after", {
    content: "foo",
    color: "red",
    fontSize: "32px"
});

https://gist.github.com/yckart/5563717


기본 클래스에서 속성 상속을 시도 할 수 있습니다.

var width = 2;
var interval = setInterval(function () {
    var element = document.getElementById('box');
    width += 0.0625;
    element.style.width = width + 'em';
    if (width >= 7) clearInterval(interval);
}, 50);
.box {
    /* Set property */
    width:4em;
    height:2em;
    background-color:#d42;
    position:relative;
}
.box:after {
    /* Inherit property */
    width:inherit;
    content:"";
    height:1em;
    background-color:#2b4;
    position:absolute;
    top:100%;
}
<div id="box" class="box"></div>


한 가지 옵션은 이미지의 속성을 사용하고 jQuery를 사용하여 수정하는 것입니다. 그런 다음 CSS에서 해당 값을 가져옵니다.

HTML (내가 가정 .cloumn하고 div있지만 그것은 무엇이든 될 수 있음) :

<div class="column" bf-width=100 >
    <img src="..." />
</div>

jQuery :

// General use:
$('.column').attr('bf-width', 100);
// With your image, along the lines of:
$('.column').attr('bf-width', $('img').width());

그런 다음 CSS에서 해당 값을 사용하려면 :

.column:before {
    content: attr(data-content) 'px';
    /* ... */
}

This will grab the attribute value from .column, and apply it on the before.

Sources: CSS attr (note the examples with before), jQuery attr.


As Boltclock states in his answer to Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery

Although they are rendered by browsers through CSS as if they were like other real DOM elements, pseudo-elements themselves are not part of the DOM, and thus you can't select and manipulate them with jQuery.

Might just be best to set the style with jQuery instead of using the pseudo CSS selector.

참고URL : https://stackoverflow.com/questions/10061414/changing-width-property-of-a-before-css-selector-using-jquery

반응형