How to add a border to an element in JavaScript: 1. Use the statement "Element object.style.border="width value style value color value""; 2. Use "Element object.style.cssText="border" :Width value style value color value "" statement.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Method 1: Use HTML DOM border attribute
Syntax: Object.style.border=borderWidth borderStyle borderColor
Example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" id="remove"> <style> div{ width: 80px; height: 30px; margin: 10px auto; } </style> </head> <body style="text-align:center;"> <p style="font-size: 19px; font-weight: bold;">单击按钮给div元素添加边框</p> <div id="div">div元素</div> <button onClick="Fun()">点击这里</button> <script> var div = document.getElementById('div'); //获取div元素对象 function Fun() { div.style.border="1px solid red"; //给div元素对象添加样式 } </script> </body> </html>
Rendering:
##2. Use cssText attribute
The essence of cssText is to set the style attribute value of HTML elements. Syntax:Object.style.cssText="Attribute name: attribute value";
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" id="remove"> <style> div{ width: 80px; height: 30px; margin: 10px auto; } </style> </head> <body style="text-align:center;"> <p style="font-size: 19px; font-weight: bold;">单击按钮给div元素添加边框</p> <div id="div">div元素</div> <button onClick="Fun()">点击这里</button> <script> var div = document.getElementById('div'); //获取div元素对象 function Fun() { div.style.cssText="border:1px dashed green"; //给div元素对象添加样式 } </script> </body> </html>
javascript advanced tutorial]
The above is the detailed content of How to add borders to elements in javascript. For more information, please follow other related articles on the PHP Chinese website!