以下是我的代码段无效:
//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 :(得分: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>
答案 1 :(得分: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>