【问题标题】:How I get percentage value instead of pixel value?我如何获得百分比值而不是像素值?
【发布时间】:2017-03-25 07:27:39
【问题描述】:
if ($C.getElement(".side-bar")) {
        $C.setEvent("click",".side-bar",function() {
            var element=document.getElementById('navbar');
            style = window.getComputedStyle(element);
            alert(style.width);
            /*if(style.width !== '60px'){
                if ( this.childElementCount == 2){
                    var nodes = this.childNodes;
                    for(var i=0; i<nodes.length; i++) {
                        if( nodes[i].className == 'nav nav-second-level'){
                            if(nodes[i].style['display'] === 'block'){ 
                                    nodes[i].style.display = '';
                                }
                            else{
                                    nodes[i].style.display= 'block';
                                }

                        }
                    }
                }
            }*/
        });
     }

在这段代码中,我需要检查导航栏的宽度,如果导航栏的宽度不等于总屏幕的 6%,那么我需要执行操作(这里给出一个导航栏宽度等于的示例60px)。当我将宽度转换为百分比而不是像素时,就会发生这种情况。谁能帮我获得百分比值而不是像素值?

我在下面添加了导航栏的结构

document.getElementById("bttn").addEventListener("click" , function (){
document.getElementById("navbar").classList.add("navbar-after-click");
});
body,html{
  width:100%;
  height:100%;
  }
#navbar{ 
 height:300px;
  background-color:blue;
  }
.navbar{
 width:15%;
}
.navbar-after-click{
  width:6%;
}
<div id="navbar" class="navbar">

</div>
<button id="bttn">click me to change the width to 6%</button>

【问题讨论】:

    标签: javascript width percentage


    【解决方案1】:

    可能没有直接的方法将值转换为百分比值。

    虽然没有测试,但你可以试试这种方式

    var yourElement = document.getElementById('someId');
    var elemWidth = window.getComputerStyle(yourElement).getPropertyValue("width");
    var parent = yourElement.parentNode;
    var parentWidth =window.getComputerStyle(parent).getPropertyValue("width");
    var calculatePercentage = (100*parseFloat(elemWidth)/parentWidth)+'%';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 2016-08-25
      相关资源
      最近更新 更多