我正在为一些同事做jQuery演示,我想演示如何使用jQuery使javascript中的某些任务变得更容易。
我想出了一个小的jQuery函数来做一些元素选择/动画,我希望向他们展示这段代码的javascript等价物。
我的问题是我的javascript有点生疏,我宁愿不想弄清楚如何使用javascript来实现它。有谁知道从jQuery生成javascript的方法?如果没有,任何人都可以推荐一个很好的资源来找到等效的javascript与jQuery的并排比较吗?
我的代码:
var move = 200;
$('#clickme').click(function() {
$('#main div:even').animate({
left:"+="+move
}, 2000);
move = -move;
});
答案 0 :(得分:2)
This article有一个很好的演示文稿,可以准确展示你试图向同事展示的内容。
它显示了这一点:
var example = null; // object
function doMove() {
example.style.left = parseInt(example.style.left)+1+'px';
setTimeout(doMove,20); // call doMove in 20msec
}
function init() {
example = document.getElementById('example'); // get the "example" object
example.style.left = '0px'; // set its initial position to 0px
doMove(); // start animating
}
window.onload = init;
可以变成这样:
$("#element").animate({ left: 100px; });
答案 1 :(得分:1)
因为jQuery是用JS实现的,而不是翻译成它(比如CoffeeScript或其他什么),所以没有准确的方法来显示一个与另一个。
您可以通过分析jQuery并显示结果来获得相同的想法 - “查看jQuery团队为我们编写的所有代码,我们基本上可以免费使用!”或者通过显示$().attr
或其他类似方法的定义来隐藏一堆特定于浏览器的怪癖。
答案 2 :(得分:1)
如果您还不知道如何在直接的JavaScript中完成任务,那么最简单的方法就是查看源代码,查看它正在做什么,并编写执行相同操作的JavaScript。 / p>
答案 3 :(得分:0)
这里有关于Javascript Animation的一些文档。您将在此处实现的其他JavaScript是关于选择元素like selecting by tag name
答案 4 :(得分:0)
我认为你可以试试
document.querySelector('#clickme')
这与jquery $(' ')
基本类似,但前一个只返回一个元素。
没有直接的方法,就好像你经历了jquery的源代码一样,你会发现使用正则表达式来解析节点选择,这对于你想要编写的每个代码都不容易实现,
这些方法之间也存在直接关系:
例如:
.click(function) -> .addEventListener('click',function,false);
答案 5 :(得分:0)
我会考虑向他们展示一系列例子,说明在jquery中做事情是多么容易 - 动画,DOM操作等。如果他们对javascript有任何了解,他们会知道它的工作量是多少保存,如果他们不知道他们为什么要做出决定?
我要提出的一个重点是,jquery中的所有内容都可以正常运行,而不会出现跨浏览器问题。
答案 6 :(得分:0)
选择器很简单,它可以转换为getElementById,但是如果它更复杂的话,可以调用Sizzle库来获取元素。
Click是bind的别名,单击指定。绑定通过添加事件来工作。这是源代码的片段:
add: function( elem, types, handler, data ) {
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
if ( handler === false ) {
handler = returnFalse;
} else if ( !handler ) {
// Fixes bug #7229. Fix recommended by jdalton
return;
}
var handleObjIn, handleObj;
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
}
// Make sure that the function being executed has a unique ID
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure
var elemData = jQuery._data( elem );
// If no elemData is found then we must be trying to bind to one of the
// banned noData elements
if ( !elemData ) {
return;
}
var events = elemData.events,
eventHandle = elemData.handle;
if ( !events ) {
elemData.events = events = {};
}
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.handle.apply( eventHandle.elem, arguments ) :
undefined;
};
}
// Add elem as a property of the handle function
// This is to prevent a memory leak with non-native events in IE.
eventHandle.elem = elem;
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = types.split(" ");
var type, i = 0, namespaces;
while ( (type = types[ i++ ]) ) {
handleObj = handleObjIn ?
jQuery.extend({}, handleObjIn) :
{ handler: handler, data: data };
// Namespaced event handlers
if ( type.indexOf(".") > -1 ) {
namespaces = type.split(".");
type = namespaces.shift();
handleObj.namespace = namespaces.slice(0).sort().join(".");
} else {
namespaces = [];
handleObj.namespace = "";
}
handleObj.type = type;
if ( !handleObj.guid ) {
handleObj.guid = handler.guid;
}
// Get the current list of functions bound to this event
var handlers = events[ type ],
special = jQuery.event.special[ type ] || {};
// Init the event handler queue
if ( !handlers ) {
handlers = events[ type ] = [];
// Check for a special event handler
// Only use addEventListener/attachEvent if the special
// events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add the function to the element's handler list
handlers.push( handleObj );
// Keep track of which events have been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
}
请注意,那里有各种聪明的东西,所以无论如何都可以。
Animate的工作原理如下:
animate: function( prop, speed, easing, callback ) {
var optall = jQuery.speed(speed, easing, callback);
if ( jQuery.isEmptyObject( prop ) ) {
return this.each( optall.complete, [ false ] );
}
// Do not change referenced properties as per-property easing will be lost
prop = jQuery.extend( {}, prop );
return this[ optall.queue === false ? "each" : "queue" ](function() {
// XXX 'this' does not always have a nodeName when running the
// test suite
if ( optall.queue === false ) {
jQuery._mark( this );
}
var opt = jQuery.extend( {}, optall ),
isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"),
name, val, p,
display, e,
parts, start, end, unit;
// will store per property easing and be used to determine when an animation is complete
opt.animatedProperties = {};
for ( p in prop ) {
// property name normalization
name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
}
val = prop[ name ];
// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
if ( jQuery.isArray( val ) ) {
opt.animatedProperties[ name ] = val[ 1 ];
val = prop[ name ] = val[ 0 ];
} else {
opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
}
if ( val === "hide" && hidden || val === "show" && !hidden ) {
return opt.complete.call( this );
}
if ( isElement && ( name === "height" || name === "width" ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height
// animated
if ( jQuery.css( this, "display" ) === "inline" &&
jQuery.css( this, "float" ) === "none" ) {
if ( !jQuery.support.inlineBlockNeedsLayout ) {
this.style.display = "inline-block";
} else {
display = defaultDisplay( this.nodeName );
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( display === "inline" ) {
this.style.display = "inline-block";
} else {
this.style.display = "inline";
this.style.zoom = 1;
}
}
}
}
}
if ( opt.overflow != null ) {
this.style.overflow = "hidden";
}
for ( p in prop ) {
e = new jQuery.fx( this, opt, p );
val = prop[ p ];
if ( rfxtypes.test(val) ) {
e[ val === "toggle" ? hidden ? "show" : "hide" : val ]();
} else {
parts = rfxnum.exec( val );
start = e.cur();
if ( parts ) {
end = parseFloat( parts[2] );
unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" ) {
jQuery.style( this, p, (end || 1) + unit);
start = ((end || 1) / e.cur()) * start;
jQuery.style( this, p, start + unit);
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] ) {
end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start;
}
e.custom( start, end, unit );
} else {
e.custom( start, val, "" );
}
}
}
// For JS strict compliance
return true;
});
}
同样,很多聪明才能确保这符合您的期望。
在现实生活中,带有事件监听器的getElementById,然后重复使用元素上的setStyle来获取动画的循环将起作用。