如何使用 Javascript 或 jQuery 选择文本光标旁边的字母?
我使用 jQuery 和 Lettering.js 将每个字母包装在带有跨度的
中,并为其提供唯一的 ID。我还在
上设置了 contenteditable=true
,这样当我单击它时,我就可以编辑文本。如何选择光标左侧或右侧的
元素,以便我可以对其应用样式?
上设置了 contenteditable=true
,这样当我单击它时,我就可以编辑文本。如何选择光标左侧或右侧的
元素,以便我可以对其应用样式?这是我的代码
<head>
<style media="screen" type="text/css">
body {text-align: center}
</style>
<script src="scripts/jquery.js" type="text/javascript" charset="utf-8"></script>
<script src="scripts/lettering.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("h1").lettering();
});
</script>
</head>
<body>
<h1 contenteditable="true" >Click me!</h1>
</body>
非常感谢任何帮助或建议!
I'm using jQuery and Lettering.js to wrap each letter in an <h1>
with a span and give it a unique ID. I've also set contenteditable=true
on the <h1>
so when I click on it I can edit the text. How would I select the <span>
element that is either to the left or right of the cursor, so I could apply styling to it?
Here's my code
<head>
<style media="screen" type="text/css">
body {text-align: center}
</style>
<script src="scripts/jquery.js" type="text/javascript" charset="utf-8"></script>
<script src="scripts/lettering.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("h1").lettering();
});
</script>
</head>
<body>
<h1 contenteditable="true" >Click me!</h1>
</body>
Would really appreciate any help or advice!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下内容适用于所有主要浏览器:
这是一个实例: http://jsfiddle.net/BATGH/1/
The following will work in all major browsers:
Here's a live example: http://jsfiddle.net/BATGH/1/
向刻字脚本创建的每个段落标签添加单击事件将为您提供被单击的元素。然后您可以使用 prev 或 next 方法获取被单击的字母之前或之后的字母。
我编写了一个示例,将显示前一封信的警报。 http://jsfiddle.net/5n5vJ/
Adding a click event to each of the paragraph tags created by the lettering script will give you the element that was clicked on. Then you can use either prev or next method to get the letter before or after the letter that was clicked.
I worked up an example that will show an alert with the previous letter. http://jsfiddle.net/5n5vJ/
这是另一个名为 Rangy 的库,它可能适合您。查看附加模块 CSSClassApplierModule。它允许您将选择内容包装在一个类中以进行样式设置。
Here's another library called Rangy which could work for you. Check out the additional module CSSClassApplierModule. It lets you wrap a selection in a class for styling.