Assigned width in percentage but want to get it in pixels

前端 未结 11 1208
北荒
北荒 2020-12-15 15:07



        
11条回答
  •  佛祖请我去吃肉
    2020-12-15 15:43

    Based on Honzik's answer there this is a small workaround in case the element needed to specify it's width is inside a hidden parent element.

    function getWidth(elemID) {
        // get parent element unique id (must have)
        var parentId = $("#"+elemID).parent().prop("id"); 
        // remove the child element based on the specified element id
        $("#"+elemID).remove();
        // append a new child element but on body where most probably is not set to "display:none"
        $("body").append('
    Hello
    '); // get the width of the newly appended child element and store it to a variable var width = $("#test2").width(); // remove child element from body $("#"+elemID).remove(); // re-append child element to its former position under former parent element (having CSS attribute "display:none") $(parentId).append('
    Hello
    '); // display stored element width alert(width); } // usage to get the element's width getWidth("test2");

    Try it in the below snippet!

    function getWidth(elemID) {
            var parentId = $("#"+elemID).parent().prop("id"); // your parent element should have a unique id specified
            $("#"+elemID).remove();
            $("body").append('
    Hello
    '); var width = $("#test2").width(); $("#"+elemID).remove(); $(parentId).append('
    Hello
    '); alert(width); } getWidth("test2");
    .test {
        border: 1px solid;
        cursor: pointer;
        height: 10px;
        position: relative;
        width: 100%;
        display:none;
    }
    
    #test2{
       width:100%;
    }
    
    
    Hello

提交回复
热议问题