Pin*_*kie 4 javascript css jquery
我正在尝试将CSS应用于所选文本.我尝试了以下,但它不起作用.我正在使用Firefox.
$(document).keyup(function(){
savedRange = selection.getRangeAt(0);
$(savedRange).wrap('<span style="color:red"></span>');
});
Run Code Online (Sandbox Code Playgroud)
我也试过了
savedRange = selection.getRangeAt(0);
$(savedRange).css('color', 'red');
Run Code Online (Sandbox Code Playgroud)
我可以使用execcommand使用contentEditable执行此操作,但execcommand应用html标记而不是内联样式.例如:<font/>而不是style="font..".我需要应用内联样式而不是已弃用的html标记.我想使用jQuery css()属性来应用样式.
Tim*_*own 13
我推荐使用我的Rangy库的CSS类应用程序模块.它适用于所有主流浏览器和任何选择.它还将打开和关闭CSS类.
以下是另一个问题的示例:如何使用html标记从window.getSelection().getRangeAt(0)中包装文本选择?
例:
<style type="text/css">
span.red {
color: red;
}
</style>
<script type="text/javascript">
var redApplier;
window.onload = function() {
rangy.init();
redApplier = rangy.createCssClassApplier("red", true);
};
function makeSelectionRed() {
redApplier.applyToSelection();
}
</script>
Run Code Online (Sandbox Code Playgroud)
UPDATE
如果使用类不是一个选项,你仍然可以使用它的变体,虽然它有点迂回:你可以使用Rangy来应用一个类,然后使用jQuery来查找这个类的跨度并将CSS添加到每个类中.这是一个例子:
function makeSelectionRed() {
var randomCssClass = "rangyTemp_" + (+new Date());
var classApplier = rangy.createCssClassApplier(randomCssClass, true);
classApplier.applyToSelection();
// Now use jQuery to add the CSS colour and remove the class
$("." + randomCssClass).css({"color": "red"}).removeClass(randomCssClass);
}
Run Code Online (Sandbox Code Playgroud)
jsFiddle:http://jsfiddle.net/z2mdw/2/
关于处理保存范围的这个问题线程可能有所帮 它没有具体告诉你如何添加CSS,但它可以帮助你包装你的范围,然后你可以链接一个.css()函数.
var range = window.getSelection().getRangeAt(0);
var newNode = document.createElement("span");
range.surroundContents(newNode);
Run Code Online (Sandbox Code Playgroud)
然后你应该能够将css应用到那个范围.
编辑:
要将CSS应用于范围选择,您可以执行以下操作.请参阅我在jsfiddle上的工作示例.
您可以使用Javascript直接在span节点上设置CSS样式:
// Get the selection range
var range = window.getSelection().getRangeAt(0);
// create a new DOM node and set it's style property to red
var newNode = document.createElement('span');
newNode.style.color = "red";
// surround the selection with the new span tag
range.surroundContents(newNode);
Run Code Online (Sandbox Code Playgroud)
或者只使用span标记包围该范围,并使用jQuery选择该span标记以使用更好的.css()语法.
// get the selection
var range = window.getSelection().getRangeAt(0);
// create a new span node and give it an id 'testing'.
var newNode = document.createElement('span');
newNode.id = "testing";
// wrap the selection range with the <span id="testing"></span> node.
range.surroundContents(newNode);
// select that new node with jquery and use the jQuery .css() method to apply styles.
$("#testing").css("color", "green");
Run Code Online (Sandbox Code Playgroud)
显然这个javascript不适合重用,因为我将ID硬编码到第二个例子中,但希望你能够根据自己的需要使用它.
| 归档时间: |
|
| 查看次数: |
8370 次 |
| 最近记录: |