简体   繁体   English

在style属性内使用CSS选择器

[英]Using CSS selectors within the style attribute

I have a nice little button which uses a lot of fancy CSS to look good. 我有一个漂亮的小按钮,它使用了很多漂亮的CSS来看起来不错。

巨大的

Here's the code behind it (I'm ignoring compatibility issues for now); 这是其背后的代码(我现在暂时忽略兼容性问题); as you can see, it uses a few selectors for hover and click events. 如您所见,它使用一些选择器来悬停和单击事件。

.button {
    display: inline-block;
    width: 200px;
    height: 200px;
    padding: 15px;
    border-radius: 25px;
    background:linear-gradient(to bottom, hsla(36, 100%, 60%, 1) 5%, hsla(36, 100%, 40%, 1) 100%);
    border:2px solid hsla(36, 100%, 30%, 1);
    box-shadow:inset 0px 2px 2px 0px white;
    position: relative;
    left: 0px;
    top: 0px;
    text-shadow:0px 1px 0px hsla(36, 100%, 30%, 1);
    margin: 25px;
}

.button:hover {
    background:linear-gradient(to bottom, hsla(36, 100%, 65%, 1) 5%, hsla(36, 100%, 45%, 1) 100%);
}

.button:active {
    background:linear-gradient(to bottom, hsla(36, 100%, 40%, 1) 5%, hsla(36, 100%, 60%, 1) 100%);
}

However, to streamline the process in the future when there will be many buttons, I instead wanted to be able to make the button have a custom attribute for colour ( buttonColor below) which will be read by some JavaScript, turned into Hue/Saturation/Lightness, and eventually changed for the many different variations. 但是,为了简化将来会有很多按钮的过程,我希望能够使按钮具有自定义的color属性(下面的buttonColor ),该属性将由一些JavaScript读取,并变为Hue / Saturation /轻巧,最终因许多不同的变化而改变。 Each button contains at least three colours; 每个按钮至少包含三种颜色。 two for the gradient and one for the drop shadow and border. 两个用于渐变,一个用于阴影和边框。

<div class="button" id="testButton"buttonColor="ff8c00">
    <p class="buttonHeader">foo</p>
    <p class="buttonBody">foo2</p>
</div>

Here's what I've got in the JavaScript: 这是我在JavaScript中获得的功能:

function hexToRgb(hex) {  //converts hexadecimal colors into Red/Green/Blue
    //code omitted for sake of conciseness
    return [r, g, b];
}
function rgbToHsl(r, g, b) { //converts Red/Green/Blue into Hue/Saturation/Lightness
    //ditto
    return [h, s, l]
}

var buttons = document.body.getElementsByClassName('button'); //Gets all elements with button class

for (var i = 0; i < buttons.length; i++) {
    var rgb = hexToRgb(buttons[i].getAttribute("buttoncolor")); //
    var hsl = rgbToHsl(rgb.r, rgb.g, rgb.b)
    //here
}

And right there is where I'm stuck. 正确的地方是我被困住的地方。

I can easily modify the style of the button, but only while it's inactive; 我可以轻松地修改按钮的样式,但前提是它必须处于非活动状态。 There's no way I've found to change how it reacts under the :hover and :active selectors. 我没有找到改变它在:hover和:active选择器下的反应的方法。

use data attributes! 使用数据属性! try something like this: 尝试这样的事情:

<div class="button" id="testButton" data-button-color="ff8c00">
    <p class="buttonHeader">foo</p>
    <p class="buttonBody">foo2</p>
</div>

js JS

function hexToRgb(hex) {
    // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
    var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, function(m, r, g, b) {
        return r + r + g + g + b + b;
    });

    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

function rgbToHsl(r, g, b){
    r /= 255, g /= 255, b /= 255;
    var max = Math.max(r, g, b), min = Math.min(r, g, b);
    var h, s, l = (max + min) / 2;

    if(max == min){
        h = s = 0; // achromatic
    }else{
        var d = max - min;
        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
        switch(max){
            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
            case g: h = (b - r) / d + 2; break;
            case b: h = (r - g) / d + 4; break;
        }
        h /= 6;
    }

    return [h, s, l];
}




var buttons = document.body.getElementsByClassName('button'); //Gets all elements with button class

for (var i = 0; i < buttons.length; i++) {
    var rgb = hexToRgb(buttons[i].data("button-color")),
        hsl = rgbToHsl(rgb.r, rgb.g, rgb.b),
        rules = [];
    rules[i][0] = hsl;

    hsl[2] = 100 - hsl[2]; // make second color
    rules[i][1] = hsl;
    var len = rules.length;
    for(;len--;) {
        buttons[i].style = 
            "background: linear-gradient(to bottom, hsla(36, 100%, "+rules[i][0]+"%, 1) 5%, hsla(36, 100%, "+rules[i][1]+"%, 1) 100%);"; // put rules on el
    }
}

edit 编辑

David Walsh has an excellent post on adding rules to stylesheets with js . David Walsh在用js向样式表添加规则方面有出色的文章。

let's say you made a rules array 假设您制作了一个规则数组

var rules = [...]; // ['float: left', 'cursor: pointer']

or object 或对象

var rules = {
    'hover': [...], // rules...
    'active': [...]
};

in your code above. 在上面的代码中。 You could then insert them with the following: 然后,您可以将它们插入以下内容:

var sheet = (function() {
    var style = document.createElement("style");
    style.appendChild(document.createTextNode(""));
    document.head.appendChild(style);
    return style.sheet;
})();

function addCSSRule(sheet, selector, rules, index) {
    if("insertRule" in sheet) {
        sheet.insertRule(selector + "{" + rules + "}", index);
    }
    else if("addRule" in sheet) {
        sheet.addRule(selector, rules, index);
    }
}

// ['float: left', 'cursor: pointer']
addCSSRules(document.styleSheets[0], ".button:hover", rules.join(';'));

or 要么

// { 'hover': ['float: left'], 'active': ['cursor: pointer']};
addCSSRules(document.styleSheets[0], ".button:hover", rules.hover.join(';'));
addCSSRules(document.styleSheets[0], ".button:active", rules.active.join(';'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM