gpt4 book ai didi

javascript - 克隆 div 并通过 onclick 更改样式

转载 作者:行者123 更新时间:2023-12-03 08:05:03 24 4
gpt4 key购买 nike

在我的 HTML 中,我有 4 个框,我想增加它们的大小并通过 onclick 出现在网站的中间。但它不适用于此克隆版本。

function changeSize(id, weight, height){
//$( "." + id ).clone().appendTo( "new" + id );
var elem = document.getElementById(id);
clone = elem.cloneNode(true); // true means clone all childNodes and all event handlers
clone.id = "newid" +id;
document.body.appendChild(clone);


if(elem.getAttribute('style')){
elem.removeAttribute('style');
} else {
elem.style.width = weight + 'px';
elem.style.height = height + 'px';
elem.style.fontSize = '30px';

elem.style.position = 'absolute';
elem.style.left= '40%';
}
}

var elems = document.getElementsByClassName('kaesten');
for(var i = 0; i < elems.length; i++){
elems[i].onclick = function(){
changeSize(this.id, 600, 600);
}
}
.kaesten{
width:240px;
height:300px;
background-color:darkgrey;
background-position:center;
background-repeat:no-repeat;
text-shadow:0px 0px 3px #000;
border: 5px solid #F0F8ff;
vertical-align:top;
text-shadow: 3px 3px 4px #777;
float:left;
margin-left:30px;
}
<div id="box1" class="kaesten">test1</div>
<div id="box2" class="kaesten">test2</div>
<div id="box3" class="kaesten">test3</div>
<div id="box4" class="kaesten">test4</div>

问题:如何通过 onclick 克隆该框并将其显示在网站中间?如何通过 onclick 删除它?

最佳答案

您可以使用 jQuery css() 方法修改 CSS:来源:http://api.jquery.com/css/

要设置指定的 CSS 属性,请使用以下语法:

css("propertyname","value");

$(document).ready(function() {
$('.kaesten').click(function() {
$('.kaesten').removeAttr('style');

var id = $(this).attr('id');
$('#' + id).css({
"width": "30em",
"height": "18em",
"top": "50%",
"left": "50%",
"position": "fixed",
"margin-top": "-9em",
"margin-left": "-15em",
"background-color": "blue"

});

});
});
.kaesten {
cursor: pointer;
width: 240px;
height: 300px;
background-color: darkgrey;
background-position: center;
background-repeat: no-repeat;
text-shadow: 0px 0px 3px #000;
border: 5px solid #F0F8ff;
vertical-align: top;
text-shadow: 3px 3px 4px #777;
float: left;
margin-left: 30px;
color: #fff;
font-family: 'helvetica';
}
.container {
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="container">
<div id="box1" class="kaesten">test1</div>
<div id="box2" class="kaesten">test2</div>
<div id="box3" class="kaesten">test3</div>
<div id="box4" class="kaesten">test4</div>
</div>

关于javascript - 克隆 div 并通过 onclick 更改样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34417204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com