2016-11-13 44 views
-1

这里是不工作的我的代码段:“切换()”工作不正常,(缩格关闭屏幕)

//code for div 3 
//When clicked the div will double in size and the text within will change and then when clicked again, all will revert back to original 
$('#div3').toggle(function(){ 
    $('#div3').animate({height: '300px', width: '300px'}); 
    document.getElementById('change-me').innerHTML="Click me to make me smaller!"; 
}, 
function(){ 
    $('#div3').animate({height: '150px', width: '150px'}); 
    document.getElementById('change-me').innerHTML="Click me to mke me bigger!"; 
}); 

每当我刷新页面,看看它是否是工作,这个代码应用的div也收缩并从页面右上角逐渐消失...

感谢任何帮助我的人。 :)

回答

0

雅,切换不功能来实现这一点。试试这个

function big() { 
 
    $('#div3').animate({ 
 
    height: '300px', 
 
    width: '300px' 
 
    }); 
 
    document.getElementById('change-me').innerHTML = "Click me to make me smaller!"; 
 
    $('#div3').off('click', big).on('click', small); 
 
} 
 

 
function small() { 
 
    $('#div3').animate({ 
 
    height: '150px', 
 
    width: '150px' 
 
    }); 
 
    document.getElementById('change-me').innerHTML = "Click me to mke me bigger!"; 
 
    $('#div3').off('click', small).on('click', big); 
 
} 
 

 
$('#div3').on('click', big);
div#div3 { 
 
    height: 150px; 
 
    width: 150px; 
 
    border: 1px solid green; 
 
}
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> 
 
<div id="div3"> 
 
    <div id="change-me"> 
 
    click me 
 
    </div> 
 
</div>

+0

感谢您的帮助家伙!非常感激! :) – JamesTheHunt

0

与原始代码的主要问题是,它的使用toggle功能,根据文档这是

显示或隐藏匹配元素。

它看起来像你想要的是切换的div3上点击大小,这样

版新增:1.0

let currSize = "small"; 
 
let config = { 
 
    small: { 
 
    size: { 
 
     height: '150px', 
 
     width: '150px' 
 
    }, 
 
    msg: "Click me to make me bigger!" 
 
    }, 
 
    big: { 
 
    size: { 
 
     height: '300px', 
 
     width: '300px' 
 
    }, 
 
    msg: "Click me to make me smaller!" 
 
    } 
 
}; 
 

 

 
$('#div3').click((e) => { 
 
    // toggle the current size 
 
    currSize = (currSize == "small") ? "big" : "small"; 
 
    
 
    // animate to the new size 
 
    $('#div3').animate(config[currSize].size); 
 
    
 
    // update the change-me text 
 
    document.getElementById('change-me').innerHTML = config[currSize].msg; 
 
});
#div3 { 
 
    height: 150px; 
 
    width: 150px; 
 
    background-color: rgba(64,64,64,0.1); 
 
    cursor: pointer; 
 
    padding: 5px; 
 
    border: 1px solid black; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div id="div3"> 
 
    Awesomest div ever, really, the best. 
 
    <div id="change-me">Click me to make me bigger!</div> 
 
</div>