基本Js函数缩放两个DIV's高度

Basic Js function to scale two DIV's heights

本文关键字:DIV 高度 两个 函数 Js 缩放 基本      更新时间:2023-09-26

如果设置,我希望#result缩放到#sidebar的高度。如果不是,则保持#result的原始高度。

我代码:

window.onload = setDiv;
function setDiv() {
    var e = document.getElementById('sidebar'); // Get the sidebar infos
    var eh = e.offsetHeight // div height
    if ( typeof(eh) == "undefined" || typeof(eh) == null)  { // if sidebar isnt in the page
        alert(eh);
        return true;
    } else {
        var eh = e.offsetHeight // div height
        var d = document.getElementById('result') // Get the result div height
        var dh = d.offsetHeight // div height
        d.style.height = eh + 65 + 'px'; // Set result div height to sidebar height
        alert(d);
        document.write(dh);
        return false;
    }
}

我不认为HTML/CSS是必要的。

谢谢。

这行好像不对:

if ( typeof(eh) == "undefined" || "null") { // if sidebar isnt in the page

试试这个:

if ( typeof(eh) == "undefined" || typeof(eh) == null) { // if sidebar isnt in the page

另外,我会添加一个try catch块。如果有抛出,你甚至不知道你的代码没有执行。

这将导致错误,因为e不存在(尚未):

var e = document.getElementById('sidebar'); // <<< This is what doesn't work

这是因为你的window.onload没有做对。去掉括号:

window.onload = setDiv;
http://jsfiddle.net/userdude/u8DZx/3/

我想演示在像jQuery这样的库中做到这一点是多么容易。window.onload并不总是像你想的那样工作;在jQuery中使用onDomReady$(document).ready()通常更好。您还可以在页面加载的不同点添加多个处理程序,仅使用window.onload方法就比较困难。

$(document).ready(function(){
    setTimeout(function(){setDiv();},2000); // So you can see the transition
});
function setDiv() {
    var $sidebar = $('#sidebar');
    if ($sidebar.size() === 0) {
        return true;
    } else {
        $('#result').animate({
            height : $('#sidebar').height()
        }, 5000);
        return false;
    }
}
http://jsfiddle.net/userdude/u8DZx/1/

如果你不想要这个效果,只需:

$('#result').height($('#sidebar').height());

如果你真的想使用offsetHeight,这听起来不像是你想要的(height代替),你可以这样做:

$(document).ready(function(){
    setTimeout(function(){setDiv();},2000); // So you can see the transition
});
function setDiv() {
    var $sidebar = $('#sidebar');
    if ($sidebar.size() === 0) {
        return true;
    } else {
        $('#result').offset($('#sidebar').offset());
        return false;
    }
}
http://jsfiddle.net/userdude/u8DZx/2/