2016-11-13 20 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>