How to pull css attributes from

How to pull css attributes from

本文关键字:attributes from css pull to How      更新时间:2023-09-26

我想弄清楚如何从CSS拉属性在Javascript中使用。我在谷歌上搜索我要找的东西太多次了,我的手指都要掉下来了。

我想改变字体大小为三种不同的字体大小:15px, 28px和40px。这将使用三个按钮进行切换。但是,当您选择字体大小时,需要更改一些其他CSS属性,以便调整文本大小和填充以与"后面"的元素对齐,这样它就不会从侧面推开,看起来很难看。我计划用Javascript自动调整大小,但是对于我的生命,我不知道如何从页面中提取"文本大小(以像素为单位)"属性,以便应用"if/else"参数。这需要在浏览器中完成,我发现了一个。getcomputedstyle命令。但是我不能让它工作,我不确定这是否是我需要的。

<body>
    <p id="spaz">Text to be resized.</p>
    <button type="button" onclick="txtszl()">large</button>
    <button type="button" onclick="txtszm()">medium</button>
    <script>
        function txtszl(){
            document.getElementById("spaz").style.fontSize="40px";
        }
        function txtszm(){
            document.getElementById("spaz").style.fontSize="28px";
        }
        var $txtelement = document.getElementById("spaz");
        var $txtsize = $txtelement.getComputedStyle("fontSize");
        if ($txtsize == 40px){
            alert("It's forty!");
        }else{
            alert("Nope!");
        }
    </script>
</body>

这就是我想出来的。任何帮助/链接将非常感激!

getComputedStyle函数返回一个CSSStyleDeclaration

var txtElementStyles = getComputedStyle($txtelement, null),
    fontSize = txtElementStyles.getPropertyValue('font-size');

工作小提琴:http://jsfiddle.net/wrathchild77/6LJaM/

function txtszl() {
         document.getElementById("spaz").style.fontSize = "40px";
         check();
     }
     function txtszm() {
         document.getElementById("spaz").style.fontSize = "28px";
         check();
     }
     function check() {
         var $txtsize = document.getElementById("spaz").style.fontSize;
         if ($txtsize == "40px") {
             alert("It's forty!");
         } else {
             alert("Nope!");
         }
     }