任何人都可以想到为什么点击事件会对a标签起作用,而不是在span?我正在创建一个富文本编辑器,并有一个粗体按钮,单击时应该使文本加粗.它只在我使用锚元素时才有效.我尝试使用跨度,没有任何反应.html是我唯一改变的东西,所以我不认为这是一个JavaScript问题.
$(document).ready(function(){
//creates the toolbar~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$('#rte').focus()
var tools = [];
tools.push('underline');
tools.push('italic');
tools.push('bold');
tools.push('justifyCenter');
tools.push('justifyLeft');
tools.push('justifyRight');
var simple_toolbar = function(){
//iterates through each tool and adds its functionality to the editor
$.each(tools, function(index,value){
$('#'+value).click(function(event){
document.execCommand( value, false, null);
$('#rte').focus();
return false;
});
//end of click function
});
//end of each iterator
};
//end of simple toolbar function
//invokes the simple toolbar.
simple_toolbar();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
});
//end of the DOM loader
Run Code Online (Sandbox Code Playgroud)
<!doctype html>
<html>
<head>
<title>An HTML5 page</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<div id="wrapper">
<div id="controls">
<!-- The only button working here is the bold because it is an <a> -->
<a href="#" id="bold"></a>
<span id="italic"></span>
<span id="underline"></span>
<span id="justifyLeft"></span>
<span id="justifyCenter"></span>
<span id="justifyRight"></span>
</div><!--end of controlls div-->
<div contenteditable="true" id="rte"></div>
<textarea id="my_form" rows="8" cols="58" ></textarea>
</div><!--end of the wrapper div-->
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
#bold{
display:block;
width:30px;
height:30px;
background-image:url('http://dl.dropbox.com/u/25006518/bold.png');
}
#italic{
display:block;
width:30px;
height:30px;
background-image:url('http://dl.dropbox.com/u/25006518/italic.png');
}
#underline{
display:block;
width:30px;
height:30px;
background-image:url('http://dl.dropbox.com/u/25006518/underline.png');
}
#justifyCenter{
display:block;
width:30px;
height:30px;
background-image:url('http://dl.dropbox.com/u/25006518/underline.png');
}
#justifyRight{
display:block;
width:30px;
height:30px;
background-image:url('http://dl.dropbox.com/u/25006518/underline.png');
}
#justifyRight{
display:block;
width:30px;
height:30px;
background-image:url('http://dl.dropbox.com/u/25006518/underline.png');
}
Run Code Online (Sandbox Code Playgroud)
这不是最好的解决方案,但我想使用跨度的唯一原因是,当您单击带有 . 的锚标记时,页面不会跳到顶部href="#"。我决定只使用锚标记,但href="#"我没有使用而是使用href="#bold". 显然,当您使用 id 选择器作为 href 属性时,页面将跳转到该元素所在的页面位置。仍然不确定为什么它不能与其他元素一起使用。我尝试摆脱迭代器并为每个按钮编写一个单独的单击事件,但它仍然只能与锚标记一起使用。