[英]How to center a button in Javascript
我試圖在 Javascript 中居中一個按鈕,以便它在頁面中水平居中。 現在,我的按鈕在我的 html 文件中,所以我不知道如何使用 CSS 將它居中,因為它是在 Javascript 中。
TLDR:在 Javascript 中,如果我 hvae 聲明了一個按鈕 btn,我應該編寫什么代碼來使其水平居中?
我在互聯網上搜索了一種使用 Javascript 將按鈕居中的方法,但無濟於事。 我希望你們都可以幫助我。
謝謝!
您可以使用CSS DOM在 javascript 中實現它
您可以使用style
關鍵字來設置元素的樣式
例如,如果您有此代碼將按鈕居中放置在 css 中
<div id="div">
<button>hi</button
</div>
div{
display: flex;
align-items: center;
你可以用javascript寫成
const div = document.getELementById("div");
div.style.display = "flex";
div.style.alignItems = "center";
這里有兩種方法可以做到這一點:
// Create button var myCenteredButton = document.createElement('button') myCenteredButton.textContent = 'Here is my centered button' // Before inserting it to the DOM, add your style myCenteredButton.style.display = 'block' myCenteredButton.style.margin = '0 auto' // Insert to DOM document.body.append(myCenteredButton)
// Create button var myCenteredButton = document.createElement('button') myCenteredButton.textContent = 'Here is my centered button' // Before inserting it to the DOM, add a class for styling with css myCenteredButton.classList.add('center-me') // Insert to DOM document.body.append(myCenteredButton)
.center-me { display: block; margin: 0 auto; }
如果我理解正確,你想將一個已經創建的按鈕居中,它可以像這樣工作:
<!--In only HTML-->
<button style="position: absolute; left: 50%; transform: translateX(-50%);">Click Me</button>
另一種方法是為按鈕設置一個 id,然后將它放在一個單獨的 CSS 文件或 <style> 標簽中,如下所示:
<!--HTML-->
<button id="myButton">Click Me</button>
/*
CSS
Remember to use a # before the name because it's an id you're trying to reach
*/
#myButton {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
或者您可以使用具有相同 HTML 基礎的 JavaScript
<!--HTML-->
<button id="myButton">Click Me</button>
然后在單獨的 JavaScript 文件或 <script> 標簽中
// Javascript
let myButton = document.querySelector("#myButton"); myButton.style.position = "absolute";
myButton.style.left = "50%";
myButton.style.transform = "translateX(-50%)";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.