是否可以在按钮上分配两个功能?

时间:2017-02-12 21:45:17

标签: javascript html css

我正在创建一个简单的文字处理器,用户可以在专用文本区域中输入任何文本,然后按三个按钮,这将使文本变为粗体,斜体并加下划线。到目前为止,我已成功完成此操作,但如果再次单击该按钮,则必须撤消更改。

即使我在onclick中插入两个函数,我似乎也无法解开文本。

<script>
	
function myFunctionBold() {
    document.getElementById("demo").style.fontWeight = "bold";
}
function myFunctionUnBold() {
    document.getElementById("demo").style.fontWeight = "normal";
}
function myFunctionItalic() {
    document.getElementById("demo").style.fontStyle = "italic";
}
function myFunctionUnderline() {
    document.getElementById("demo").style.textDecoration = "underline";
}
</script>
<style>
.buttonsBold {
      height: 21px;
	  cursor: pointer;
	  display:inline-block;
	  margin: 5px 4px;
      font-weight: bolder;
}
.buttonsItalic {
      height: 21px;
	  cursor: pointer;
	  display:inline-block;
	  margin: 5px 4px;
	  font-style: italic;
}
.buttonsUnderline {
      height: 21px;
	  cursor: pointer;
	  display:inline-block;
	  margin: 5px 4px;
	  text-decoration: underline;
}
</style>
<body>
<p>This is a simple word processor.<br>
Type some text in the text area and press the buttons!
</p>
<form action="textarea"> 
Enter text here:<br>
<input id="demo" type="text" name="yourText">
</form>
<br>

<button class="buttonsBold" onclick="myFunctionBold(); myFunctionUnBold();" >Bold</p>
<button class="buttonsItalic" onclick="myFunctionItalic()">Italic</p>
<button class="buttonsUnderline" onclick="myFunctionUnderline()">Underline</p>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

您通常应避免使用内联JavaScript。更简洁的方法是使用单独的脚本和addEventListener(),您可以轻松地分配任意数量的函数:

var btn = document.getElementById('btn');

btn.addEventListener('click', doThis);
btn.addEventListener('click', doThat);

function doThis() {
   alert("done this");
}

function doThat () {
  alert("done that");
}
<button id="btn">Click</button>

答案 1 :(得分:0)

你不需要在点击时调用两个函数,你可以在一个函数内逻辑地连接它,

function toggleBold() {
    if(document.getElementById("demo").style.fontWeight == "bold"){
        document.getElementById("demo").style.fontWeight = "normal"
    }else{
    document.getElementById("demo").style.fontWeight = "bold"
    }
}

此功能将切换为粗体。

演示:https://jsfiddle.net/nvujtne7/

相关问题