JS Operation example of creating and manipulating external styles

Source: Internet
Author: User

Compatible with IE8 and above IE browser
1. [Code][html] Code
<! DOCTYPE html>
<meta charset= "Utf-8" >
<title></title>
<body>
<div id= "Test" ></div>
</body>
<script src= ". /lib/jquery-1.8.3.min.js "></script>
<script>
/*
* Firefox no addRule, low version ie no insertrule,insertrule is the standard
* The code here Insertrule-Addrule is because Inserterrule only
* 2 parameters. 2 parameters to 3 parameters more than one
*/
if (! CSSStyleSheet.prototype.insertRule) {
CSSStyleSheet.prototype.insertRule = function (style, index) {
if (!style) {
Return
}
var style = Style.split ("{");
if (style.length<2) {
Return
}
This.addrule (Style[0], Style[1].split ("}") [0], index);
}
}

/*
* Firefox no removerule, low version ie no deleterule
* Delete? Rule is a network of standard pitch
*/http://www.huiyi8.com/yinxiao/?
if (! CSSStyleSheet.prototype.deleteRule) {
CSSStyleSheet.prototype.deleteRule = function (index) {
This.removerule (index);
}
}

/**
* Create an external style sheet
*/
function Sheet (appendTo) {
var style = document.createelement ("style");
Style.type = ' text/css ';
AppendTo? Appendto.append (Style): $ ("Body"). Append (style);
Return Style.sheet? Style.sheet:style.styleSheet;
}

var sheet = new sheet ();
Sheet.insertrule ("#test {width:100px;height:100px;background:red;border:5px solid green;}", 0);
Sheet.insertrule ("#test {position:absolute;}", 1);
Sheet.insertrule ("#test {position:absolute;}", 2);

var mouseDown = false;
var position;
var style;
var target = $ ("#test");
var x, y;
var rule;
$ ("#test"). MouseDown (function (e) {
MouseDown = true;
x = E.clientx;
y = e.clienty;
Position = Target.position ();
}). MouseMove (function (e) {
if (MouseDown = = True) {
Rule = sheet.cssrules? SHEET.CSSRULES[2]: sheet.rules[2];
Rule.style.top = (position.top + e.clienty-y) + "px";
Rule.style.left = (Position.left + e.clientx-x) + "px";
}
}). MouseUp (function () {
MouseDown = false;
});
</script>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.