我有以下代码。
HTML在下面。
<div class="normal">
<p>This is Paragraph No.1</p>
<p>This is Paragraph No.2</p>
<p>This is Paragraph No.3</p>
<p>This is Paragraph No.4</p>
<p>This is Paragraph No.5</p>
</div>
CSS在
之下.normal {
color: #808080;
border: 4px solid blue;
border-radius: 50px 50px;
width: 800px;
font-family: 'Comic Sans MS';
margin: auto;
margin-top: 10px;
font-size: 30px;
-webkit-transform: rotate(10deg);
}
.change {
color:#ffd800;
border: 6px solid orange;
border-radius: 50px 50px;
width: 800px;
font-family: 'Comic Sans MS';
margin: auto;
margin-top: 10px;
font-size: 30px;
-webkit-transform: rotate(20deg);
}
我想要的是在正常和切换div元素内部之间切换我的div类。 我知道如何使用 jQuery ,但我想使用纯javascript?
以下是我的尝试
(function () {
var pElement = document.getElementsByClassName("normal");
pElement.onclick = function () {
//what to do here
};
} ());
答案 0 :(得分:6)
getElementsByClassName返回元素列表,而不是单个元素。因此,您需要从中获取第一个元素,它实际上是指您的div。代码看起来像这样:
var pElements = document.getElementsByClassName("normal");
var pElement = pElements[0];
pElement.onclick = function () {
if (this.getAttribute("class") == "normal")
this.setAttribute("class", "change")
else
this.setAttribute("class", "normal");
};
正如RobG所说,仍在使用的旧浏览器不支持document.getElementsByClassName()
。这主要是IE8及以下。作为替代方案,您可以使用document.querySelectorAll(".normal")
。注意类名前面的.
(它是一个CSS选择器)。由于您只需要一个元素,因此您也可以使用document.querySelector(".normal")
来获取该元素。
这实际上可能更容易,因为这些是jQuery使用的选择器,因此在本机jQuery之间来回切换可能更容易。
您可以使用className
属性设置类,而不是使用get / setAttribute。
将所有内容整合在一起,更新的代码如下所示:
var pElement = document.querySelector(".normal");
pElement.onclick = function () {
if (this.className == "normal")
this.className = "change";
else
this.className = "normal";
};
答案 1 :(得分:5)
如果浏览器支持不是问题,您可以使用toggle()
method/classList
。
(function () {
var pElement = document.getElementsByClassName("normal")[0];
pElement.addEventListener('click',function(){
pElement.classList.toggle('change');
});
} ());
答案 2 :(得分:0)
(function () {
var pElements = document.getElementsByClassName("normal");
for ( p in pElements ) {
p.onclick = function () {
if ( this.className.indexOf('normal') > -1 ) {
this.className = 'change';
} else {
this.className = 'normal';
}
};
}
} ());
尚未测试,但这应该可以解决问题。
答案 3 :(得分:0)
如果你想要一些跨浏览器的东西,使用纯粹的javascript(不使用像jQuery这样的库),那么你需要这样的东西(这与@JoshCrozier的答案类似,但是会抛出大量的兼容性功能如果它们可用,它将默认为本机。底部有一个UMD允许您使用模块加载器,以便您可以将它们保存在一个单独的文件中 - 一个库。 ===好玩什么? :)
Javascript - 兼容性位
/*global window, document, module, define, $ */
(function () {
'use strict';
var commands = {},
MAX_UINT32 = 4294967295,
baseFunction = function () {
return;
},
privateUndefined = (baseFunction()),
hasOwn = commands.hasOwnProperty,
toClass = commands.toString,
trimFN = ''.trim,
baseArray = [],
slice = baseArray.slice,
forEachFN = baseArray.forEach,
filterFN = baseArray.filter,
$ = {},
makeRegex;
function isFunction(arg) {
return typeof arg === 'function';
}
function throwIfNotFunction(arg) {
if (!isFunction(arg)) {
throw new TypeError('is not a function');
}
return arg;
}
function isUndefined(arg) {
return privateUndefined === arg;
}
function isNull(arg) {
return null === arg;
}
function isUndefinedOrNull(arg) {
return isUndefined(arg) || isNull(arg);
}
function isObject(arg) {
return toClass.call(arg) === '[object Object]';
}
function isString(arg) {
return typeof arg === 'string';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isBoolean(arg) {
return typeof arg === 'boolean';
}
function handler(object, evt, func) {
var ret;
if (evt) {
ret = func.call(object, evt);
if (false === ret) {
evt.stopPropagation();
evt.preventDefault();
}
} else {
window.event.target = window.event.srcElement;
ret = func.call(object, window.event);
if (false === ret) {
window.event.returnValue = false;
window.event.cancelBubble = true;
}
}
return ret;
}
$.addEventListener = function (object, type, func) {
var uid = type + ':' + func,
euid = 'e:' + uid;
object[euid] = func;
if (isFunction(object.addEventListener)) {
object[uid] = function (evt) {
handler(object, evt, object[euid]);
};
object.addEventListener(type, object[uid], false);
} else if (isObject(object.attachEvent)) {
object[uid] = function () {
handler(object, null, object[euid]);
};
object.attachEvent('on' + type, object[uid]);
} else {
throw new Error('Handler could not be added.');
}
};
$.removeEventListener = function (object, type, func) {
var uid = type + ':' + func,
euid = 'e:' + uid;
if (isFunction(object.removeEventListener)) {
object.removeEventListener(type, object[uid], false);
} else if (isObject(object.detachEvent)) {
object.detachEvent('on' + type, object[uid]);
} else {
throw new Error('Handler could not be removed.');
}
object[euid] = null;
object[uid] = null;
delete object[euid];
delete object[uid];
};
if (isFunction(trimFN)) {
$.trim = function (text) {
return trimFN.call(text);
};
} else {
$.trim = function (text) {
return text.replace(/^\s+|\s+$/g, '');
};
}
if ('classList' in document.body) {
$.classList = {
contains: function (node, className) {
return node.classList.contains(className);
},
add: function add(node, className) {
node.classList.add(className);
},
remove: function (node, className) {
node.classList.remove(className);
},
toggle: function (node, className) {
node.classList.toggle(className);
}
};
} else {
makeRegex = function (className, flags) {
return new RegExp('(?:^|\\s)' + className + '(?!\\S)', isString(flags) ? flags : '');
};
$.classList = {
contains: function (node, className) {
return !!node.className.match(makeRegex(className));
},
add: function add(node, className) {
if (!$.classList.contains(node, className)) {
node.className = $.trim(node.className);
if (node.className) {
node.className += ' ';
}
node.className += className;
}
},
remove: function (node, className) {
if ($.classList.contains(node, className)) {
node.className = $.trim(node.className.replace(makeRegex(className, 'g'), ''));
}
},
toggle: function (node, className) {
if ($.classList.contains(node, className)) {
$.classList.remove(node, className);
} else {
$.classList.add(node, className);
}
}
};
}
function checkObjectCoercible(inputArg) {
if (isUndefinedOrNull(inputArg)) {
throw new TypeError('Cannot convert "' + inputArg + '" to object');
}
return inputArg;
}
function argToObject(inputArg) {
var object = checkObjectCoercible(inputArg);
if (isBoolean(object) || isNumber(object) || isString(object)) {
object = commands.constructor(object);
}
return object;
}
function clamp(number, min, max) {
return Math.min(Math.max(number, min), max);
}
if (isFunction(forEachFN)) {
$.forEach = function (array) {
return forEachFN.apply(array, slice.call(arguments, 1));
};
} else {
$.forEach = function (array, fn, thisArg) {
var object = argToObject(array),
length,
index;
throwIfNotFunction(fn);
for (index = 0, length = clamp(object.length, 0, MAX_UINT32); index < length; index += 1) {
if (hasOwn.call(object, index)) {
fn.call(thisArg, object[index], index, object);
}
}
};
}
if (isFunction(filterFN)) {
$.filter = function (array) {
return filterFN.apply(array, slice.call(arguments, 1));
};
} else {
$.filter = function (array, fn, thisArg) {
var object = argToObject(array),
next,
length,
arr,
index,
element;
throwIfNotFunction(fn);
for (arr = [], next = index = 0, length = clamp(object.length, 0, MAX_UINT32); index < length; index += 1) {
if (hasOwn.call(object, index)) {
element = object[index];
if (fn.call(thisArg, element, index, object)) {
arr[next] = element;
next += 1;
}
}
}
return arr;
};
}
if ('getElementsByClassName' in document) {
$.getElementsByClassName = function (elementNode, className) {
return elementNode.getElementsByClassName(className);
};
} else {
$.getElementsByClassName = function (elementNode, className) {
return $.filter(elementNode.getElementsByTagName('*'), function (element) {
return $.classList.contains(element, className) ? element : privateUndefined;
});
};
}
if (typeof module === 'object' && module && typeof module.exports === 'object' && module.exports) {
module.exports = $;
} else if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
define($);
} else {
window.$ = $;
}
}());
Javascript - 实际代码。
$.forEach($.getElementsByClassName(document, 'normal'), function (element) {
$.addEventListener(element, 'click', function () {
$.classList.toggle(element, 'change');
});
});
上