使用Math.max

时间:2015-09-29 08:23:00

标签: javascript

嘿伙计们,我认为这很简单,但我面临的问题是获得元素offsetWidth的最大值。控制台不会返回最大宽度或高度。

示例:

<div style="left:30px;top:166px;position:absolute">
            <img src="assets/text1.png" />
        </div>
        <div style="left:350px;top:266px;position:absolute">
            <img src="assets/text2.png" />
        </div>
        <div style="left:350px;top:366px;position:absolute">
            <img src="assets/text3.png" />
        </div>

<script>
   elements = document.querySelectorAll("#container > div");
elementsArray = [];

for (var j = 0; j < nrOfElements; j++) {
    elementsArray.push(elements[j]);
}

    var width = elementsArray[0].offsetWidth;
    var height = elementsArray[0].offsetHeight;

    for (var i = 0; i < nrOfElements; i++) {
        var maxWidth = Math.max(width, elementsArray[i].offsetWidth);
        var maxHeight = Math.max(height, elementsArray[i].offsetHeight);
        var minWidth = Math.min(width, elementsArray[i].offsetWidth);
        var minHeight = Math.min(height, elementsArray[i].offsetHeight);
    }
        console.log("maxWidth " + maxWidth);
        console.log("maxHeight " + maxHeight);
        console.log("minWidth " + minWidth);
        console.log("minHeight " + minHeight);
</script>

注意

它应该返回:

maxWidth = 380 (second element);
maxHeight = 70 (third element);
minWidth = 200 (third element);
minHeight = 59 (first element);

它返回:

maxWidth = 296 (first element);
maxHeight = 59 (second and third element height);
minWidth = 200 (its ok);
minHeight = 59 (its ok);

什么错了?哪里我错了?

纯粹的js拜托!

由于

修改

正如大家建议的那样,新代码如下:

var width = minW = elementsArray[0].offsetWidth;
    var height = minH = elementsArray[0].offsetHeight;

    var maxWidth;
    var maxHeight;
    var minWidth;
    var minHeight;

    for (var i = 0; i < nrOfElements; i++) {
        var eachElem = elementsArray[i];
        maxWidth = Math.max(width, elementsArray[i].offsetWidth);
        maxHeight = Math.max(height, elementsArray[i].offsetHeight);
        minWidth = Math.min(width, elementsArray[i].offsetWidth);
        minHeight = Math.min(height, elementsArray[i].offsetHeight);
    }
        console.log("maxWidth " + maxWidth);
        console.log("maxHeight " + maxHeight);
        console.log("minWidth " + minWidth);
        console.log("minHeight " + minHeight);

修改2

我生气了!小提琴检查它,用F12它应该检查控制台,或更改控制台以提醒...

http://jsfiddle.net/ef4wvuy6/

2 个答案:

答案 0 :(得分:1)

以下是更新后的JSFiddle。你必须确保在Math.min / max函数中使用临时的最小/最大变量,而不仅仅是你最初设置的宽度/高度(这是你最新的JSFiddle中的错误)。

UPDATE Table_name SET field_name = replace(field_name, 'unwanted_text', 'wanted_text')
     WHERE language = "it-IT"

答案 1 :(得分:1)

您可以通过此代码eval("Math.max("+arrWidth.toString()+")");

从数组中获取最大(或最小)元素

Demo

更新:您应该使用elementsArray[i].firstElementChild.offsetHeight获取offsetHeight的{​​{1}}