簡體   English   中英

如何在document.write()中使用樣式標記內的javascript變量定位div

[英]How to use a javascript variable inside style tag for positioning a div by document.write()

我正在嘗試在指定位置使用javascript document.write()創建一個div。

這給出了正確的答案

document.write("<div style='position: absolute; left:200px; top:100px;'<h1 style='font-size:10px; color:blue;'> HELLO WORLD<h1></div>");

但是每當我在頂部和左側使用javascript變量時,左側都會給出正確的位置,但頂部不會

document.write("<div style='position: absolute; left: " + left + "px; top: " + top + "px;'>" + "    <h1 style='font-size:10px; color:blue;'> HELLO WORLD<h1></div>"); 

如何在頂部使用javascript變量?

因為top等同於window.top ...請使用其他變量名稱,或將代碼包含在函數或IIFE中。

–由Jaromanda X回答

請將您的變量名top更改為其他名稱,例如top2等。

頂部是JavaScript中的Windoww對象。

這是顯示它的示例。

var top = 100;  // not ok (it's Window Object)
var top2 = 100; // ok
var left = 200; // ok

/* top */
console.log(alert("<div style='position: absolute; left:" + top +"px; top:" + left + "px;'> <h1 style='font-size:10px; color:blue;'> HELLO WORLD </h1></div>"));
// <div style='position: absolute; left:[object Window]px; top:200px;'> <h1 style='font-size:10px; color:blue;'> HELLO WORLD </h1></div>


/* top2 */
<div style='position: absolute; left:[object Window]px; top:200px;'> <h1 style='font-size:10px; color:blue;'> HELLO WORLD </h1></div>
// <div style='position: absolute; left:100px; top:200px;'> <h1 style='font-size:10px; color:blue;'> HELLO WORLD </h1></div

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM