简体   繁体   中英

Get text content width in parent with overflow hidden

I'm trying to have a similar functionality as Excel double clicking the column re-sizer and expanding particular column to max width of content in that column.

Problem: I don't know how to get text content width inside div with overflow hidden and text-overflow ellipsis. And I'm not sure what tricks I need to apply for this to work. I never tried something like this.

Current HTML markup:

<div style="width: @manuallySetWidthInPx">text</div>

Current CSS:

position: relative;
min-width: 50px;
float: left;
padding: 5px;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
white-space: nowrap;
overflow: hidden;
-ms-text-overflow: ellipsis;
-o-text-overflow: ellipsis;
text-overflow: ellipsis;

How I need to re-factor <div /> and css to get inner text content actual width?
I'm ok with using jQuery .

Note: I'm trying to achieve this while keeping text-ellipsis, so if I need to clone that row I'm good with that.

I make a DIV and place it off screen with the following CSS

#two{
    width: auto !important;
    top: -100px;
}

HTML

<div id = "one">
    gibbfasdfsdfasdfasdfasdfasdfASDadsAS
</div>

<div id = "two">


</div>

Then using the following JavaScript to transfer the text of the shown DIV to the hidden DIV and grab the hidden DIV's width.

$(document).on("click", "#one", function(){
    var value = $("#one").text();
    $("#two").text(value);
    var div_width = $("#two").width();
    alert(div_width);
});

Fiddle here

Depending on the context you use the above JavaScript code, there could be some performance issues. I don't see any problems with running a loop for 200 iterations though

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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