这种方法使用jQuery的,但我坚持用本地DOM方法大部分:
function actOnElem(el, method, duration) {
// if no passed 'el' or 'method' return
if (!el || !method) {
return false;
}
else {
// if 'el' is an element-node, use 'el' else assume it's an id
el = el.nodeType == 1 ? el : document.getElementById(el);
// duration is used if passed, otherwise 'slow' is used as the default
duration = duration || 'slow';
// create a jQuery object from 'el',
// call the method, if it exists,
// and use the 'duration'
$(el)[method](duration);
}
}
actOnElem(document.getElementById('two'), 'slideDown', 1000);
JS Fiddle demo。
请注意,有没有合理性检查,因此,如果元素已经可见,你选择用slideDown
那么什么都不会发生作用。不过在我认为这个回答你的问题,我完全不清楚为什么要采取这种方法,而不是在jQuery的方法直接调用。
稍微修改后的功能,允许一个(非常简单)故障报告:
function actOnElem(el, method, duration, debug) {
if (!el || !method) {
return false;
}
else {
el = el.nodeType == 1 ? el : document.getElementById(el);
duration = duration || 'slow';
if ($(el)[method]) {
$(el)[method](duration);
}
else if (debug) {
console.log('Did you make a typo? There seems to be no "' + method + '" method.');
}
}
}
actOnElem(document.getElementById('two'), 'slidedown', 1000, true);
// ^
// +--- typo, should be 'slideDown'
JS Fiddle demo。