下面是一个更通用的解决方案,您可以使用它来更改节点的属性并恢复该属性的先前值。支持 JQuery 和纯 javascript:
function attributeMutation (node) {
this.node = node;
this.isJQuery = (Object.prototype.toString.call(node) === "[object Array]");
this.store = {};
}
attributeMutation.prototype.change = function (name) {
this.name = name;
return this;
}
attributeMutation.prototype.to = function (value) {
if (this.isJQuery) {
this.store[this.name] = this.node.attr(this.name);
this.node.attr(this.name, value);
} else {
this.store[this.name] = this.node.getAttribute(this.name);
this.node.setAttribute(this.name, value);
}
}
attributeMutation.prototype.restore = function (name) {
var currentValue;
if (this.isJQuery) {
currentValue = this.node.attr(name);
this.node.attr(name, this.store[name]);
} else {
currentValue = this.node.getAttribute(name);
this.node.setAttribute(name, this.store[name]);
}
this.store[name] = currentValue;
}
用法是:
var mapCanvas = document.getElementById("map_canvas")
, mapCanvasAttributes = new attributeMutation(mapCanvas)
, screenres = screen.width + 'x' + screen.height;
if (screenres == "1920x1080") {
mapCanvasAttributes.change('height').to('1000px');
}
if (screenres == "1366x768") {
mapCanvasAttributes.change('height').to('6000px');
}
// and to restore to the previous height
mapCanvasAttributes.restore('height');