如何在oldschool javascript div中添加换行符

时间:2018-04-17 00:10:05

标签: javascript

我必须以某种方式更改以下代码,以便为AddRemoteButtonText生成的按钮上的标签添加换行符。尝试了我在这个网站上发现的一切,但没有任何工作(很可能是因为我刚刚开始编写javascript)。大多数尝试在函数中添加另一个变量,然后通过" \ n"来实现它。

    var size = 20;
var repeat_timer;

function AddRemoteButtonText(num, posx, posy, wx, wy, color, label, remote, command, initial_delay, repeat_delay) 
{
    document.write('<div id="' + num + '" class="button ' + color + '" style="position:absolute; top:' + posy + 'px; left:' + posx + 'px; height:' + wy + 'px; width:' + wx + 'px; line-height: ' + wy + 'px;" align="center">' + label + '</div>');
    document.getElementById(num).onmouseup = function () { SendIRCommand (num,remote,command,initial_delay,repeat_delay); EndSendCommand (num) };
    document.getElementById(num).onmouseleave = function () { EndSendCommand (num) };
}

    }
};

感谢您的回答!

2 个答案:

答案 0 :(得分:0)

添加'<br>',例如以下示例

document.write(variable +'<br/>'+ variable2);

答案 1 :(得分:0)

我可能会这样做(简化为例):

var i = 0;
var aboveLineBreak;
var belowLineBreak;

function AddRemoteButtonText() {
  console.log(i);
  //define some text to print to the button
  aboveLineBreak = "above br" + i;
  belowLineBreak = "below br" + i;
  //create a button object
  var btn = document.createElement("DIV");
  
  //add our text, including the line break, to the button
  btn.appendChild(document.createTextNode(aboveLineBreak));
  btn.appendChild(document.createElement("BR"));
  btn.appendChild(document.createTextNode(belowLineBreak));
  //define our button's CSS style
  btn.setAttribute("class", "button red");
  //to set the position, do:
  //btn.style.position = "absolute";
  //btn.style.top = whatever;
  //and so on...
  //add listeners if needed...
  btn.onmouseup = function () { console.log("foo"); };
  //finally add the button to the document's body and increment i
  document.body.appendChild(btn);
  i++;
}
.button {
  width: 33%;
  height: 45px;
}

.red {
  background-color: darkred;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
</head>

<body>
  <button onClick="AddRemoteButtonText();"> Add Remote Button Text </button>
</body>

</html>

不是最漂亮的按钮,但如果您只是用自己的CSS替换我的CSS,那么应该有一个工作换行符。如果没有,我们将需要您发布您的CSS,以便我们查看它。