Javascript操作剪切板数据(支持IE、Chrome、360、搜狗),亲测!

时间:2022-05-29 08:47:34

clipboarddata只能在IE浏览器中使用,在chrome下会提示对象未定义!以下的方法支持IE、Chrome、360、搜狗等浏览器,其它浏览器还未验证。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,Chrome=1">
<title>js操作剪切板测试</title>
<script>
var EventUtil = {
addHandler: function (element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else if (element.attachEvent) {
element.attachEvent("on" + type, handler);
} else {
element["on" + type] = handler;
}
},
getEvent: function (event) {
return event ? event : window.event;
},
getClipboardText: function (event) {
var clipboardData = (event.clipboardData || window.clipboardData);
return clipboardData.getData("text");
},
setClipboardText: function (event, value) {
if (event.clipboardData) {
return event.clipboardData.setData("text/plain", value);
} else if (window.clipboardData) {
return window.clipboardData.setData("text", value);
}
},
preventDefault: function (event) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
};
</script>
</head> <body>
<form name="f1">
文本框:<input type="text" name="textbox1" id="textbox1" value=""/>
</form>
</body>
<script>
var textbox = document.forms[0].elements["textbox1"]
EventUtil.addHandler(textbox, "paste", function (event) {
event = EventUtil.getEvent(event);
var text = EventUtil.getClipboardText(event);
alert(text.length);
//if (!/^\d*$/.test(text)) {
EventUtil.preventDefault(event);//取消粘贴
//}
}); </script>
</html>

参考自:http://blog.csdn.net/qwlovedzm/article/details/18412193

    http://www.w3cmm.com/javascript/operation-clipboard.html