JavaScript 如何更改div的边框宽度
div元素在创建现代Web应用程序时非常重要,并且通过动态修改其属性可以增强用户体验。在本文中,我们将看到如何使用JavaScript更改div元素的边框宽度。
CSS中的border-width属性用于指定HTML元素周围边框的宽度。它接受以像素、ems、rems或百分比为单位的值,并且可以独立设置每个边框的宽度。要使用JavaScript更改div元素的边框宽度,我们需要定位div元素并设置其border-width属性。
语法:
element.style.borderWidth = "px"
示例1: 在以下示例中,我们首先使用ID获取具有类名为card的div元素,使用document.getElementById()方法。然后,我们使用style.borderWidth方法将元素的borderWidth样式属性设置为5px。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>GeeksforGeeks</title>
<style>
.card {
border: 1px solid green;
padding: 10px;
margin: 10px;
width: 50%;
}
</style>
</head>
<body>
<div class="card" id="myCard">
<div class="card-body">
<h1 class="card-title">
Welcome To Geeksforgeeks!!
</h1>
</div>
</div>
<script>
let myCard = document.getElementById("myCard");
myCard.style.borderWidth = "5px";
</script>
</body>
</html>
输出:
示例2: 在下面的示例中,我们首先通过其ID获取div元素。 然后,我们将borderTopWidth设置为2px,borderTopWidth设置为4px,borderRightWidth设置为8px,borderLeftWidth设置为12px。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible"
content="IE=edge">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>GeeksforGeeks</title>
<style>
div {
padding: 10px;
width: 60%;
border: 2px solid green;
border-radius: 10px;
}
</style>
</head>
<body>
<div id="gfg">
<h1>Welcome To Geeksforgeeks!!</h1>
<p>
A Computer Science Portal for geeks.
It contains well written, well thought
& well explained computer science & pro-
gramming articles.
</p>
</div>
<script>
let myDiv = document.getElementById("gfg");
myDiv.style.borderTopWidth = "2px";
myDiv.style.borderRightWidth = "4px";
myDiv.style.borderBottomWidth = "8px";
myDiv.style.borderLeftWidth = "12px";
</script>
</body>
</html>
输出: