如何用jQuery删除CSS top和left属性
方法1:使用css()方法:css()方法用于获取或设置一个选定元素的CSS属性。它需要两个参数,第一个参数是需要设置的属性,第二个参数是需要设置的值。
通过使用’initial’值可以有效地禁用’top’值,这将把该属性设置为其默认值。这与’左’值的做法类似。这将删除元素中’top’和’left’值的效果。
语法:
function removeTopLeft() {
('selectedElement').css('top', 'initial');
('selectedElement').css('left', 'initial');
}
示例:
<!DOCTYPE html>
<html>
<head>
<title>
How to Remove CSS "top" and
"left" attribute with jQuery?
</title>
<style>
.box {
position: absolute;
top: 250px;
left: 200px;
height: 100px;
width: 100px;
background-color: green;
}
</style>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js">
</script>
</head>
<body>
<h1 style="color: green">
GeeksForGeeks
</h1>
<b>
How to Remove CSS “top” and
“left” attribute with jQuery?
</b>
<p>
Click on the button to remove
the top and left attribute.
</p>
<button onclick="removeTopLeft()">
Remove top and left
<div class="box"></div>
<script type="text/javascript">
function removeTopLeft() {
('.box').css('top', 'initial');
('.box').css('left', 'initial');
}
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
方法2:使用顶部和左边的属性:顶部和左边的值可以在元素的样式属性的帮助下通过访问这些属性来改变。首先使用jQuery选择器选择所需的元素。样式属性和它的 “top “和 “left “值,然后使用点符号访问所选对象。
通过使用’initial’值可以有效地禁用’top’值,这将把该属性设置为其默认值。这与’左’值的做法类似。这将删除元素中’top’和’left’值的效果。
语法:
function removeTopLeft() {
('selectedElement')[0].style.top = "initial";
('selectedElement')[0].style.left = "initial";
}
示例:
<!DOCTYPE html>
<html>
<head>
<title>
How to Remove CSS "top" and
"left" attribute with jQuery?
</title>
<style>
.box {
position: absolute;
top: 250px;
left: 200px;
height: 100px;
width: 100px;
background-color: green;
}
</style>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js">
</script>
</head>
<body>
<h1 style="color: green">
GeeksForGeeks
</h1>
<b>
How to Remove CSS “top” and
“left” attribute with jQuery?
</b>
<p>
Click on the button to remove
the top and left attribute.
</p>
<button onclick="removeTopLeft()">
Remove top and left
<div class="box"></div>
<script type="text/javascript">
function removeTopLeft() {
('.box')[0].style.top = "initial";
('.box')[0].style.left = "initial";
}
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。