以下は、ノードの属性を変更し、その属性の以前の値を復元するために使用できる、より一般的なソリューションです。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');