Js cannot get the width of a hidden div but only after it is displayed

  • 2020-03-30 03:51:40
  • OfStack


var tipsWidth = $(".Loading").css("width").replace("px", "") //First get
var windowWidth = $(window).width(); 
$(".Loading").css({ "display": "block" }); //Show again
$(".Loading").css({ "left": (windowWidth - tipsWidth) / 2 + "px" }); 

I want to get a adaptive width based on the content of the actual width of the div, the initial div is hidden, I want to get the actual width of the it, centered on his operation, and made a long time, always get less than the actual width of the div, later found js can't get the width of the hidden div, now is to display the first, to get its width, position calculation


$(".Loading").css({ "display": "block" });//First show
var tipsWidth = $(".Loading").css("width").replace("px", "") //To obtain
var windowWidth = $(window).width(); 
$(".Loading").css({ "left": (windowWidth - tipsWidth) / 2 + "px" });

Related articles: