如何在javascript中找到元素的实际宽度

How to find the actual width of element in javascript

本文关键字:元素 javascript      更新时间:2023-09-26

嗨,我正试图找到给定元素的实际宽度,并弹出显示实际宽度的警告。

我使用的代码在这里..

html元素
<table cellspacing="1" cellpadding="5" style=";width:975px;border: 1px solid black;" id="menu_bar">

我正在使用这个:

var widthofmenubar = $(this).find("#menu_bar").width;

Try like

var widthofmenubar = $("#menu_bar").width();

和编辑你的HTML像

<table cellspacing="1" cellpadding="5" style="width:975px;border: 1px solid black;" id="menu_bar">

添加()后,需要执行.width()方法

var widthofmenubar = $(this).find("#menu_bar").width();
var widthofmenubar = $("#menu_bar").width();
Try this:

First you edit your code, remove ';' after style attr
Correct Code is:
<table cellspacing="1" cellpadding="5" style="width:975px;border: 1px solid black;" id="menu_bar">
Not
<table cellspacing="1" cellpadding="5" style=";width:975px;border: 1px solid black;" id="menu_bar">
// Get Table Width by ID
var tableWidth = $('#menu_bar').css('width');
alert(tableWidth ); // will alert table width

$(this).find("#menu_bar").width();表示实际显示宽度(渲染),$(this).find("#menu_bar").css('width')表示应用宽度

在jquery中有两个方法;1) .innerWidth2) .outerwidth

innerwidth不计算边距宽度,outerWidth计算边距宽度

$('#menu_bar').innerWidth();
$('#menu_bar').outerWidth();