- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个working tool (请参阅第一个代码块),我想在其中包含单击并按住功能。
我想在按住左按钮时快速加,在按住右按钮时快速减。就像它已经具有的单击功能一样,但是是一个更快的选项。
我是一个完全的新手,所以非常感谢工作演示。谢谢。
代码:
<!DOCTYPE html>
<html>
<head>
<script>
var Alexander =
{
Strength: "AlexanderStrengthVal",
Bonus: "AlexanderRemainingBonusVal",
Limits: {
Strength: {
max: 80,
min: 60
}
}
};
function add(character, stat)
{
var txtNumber = document.getElementById(character[stat]);
var newNumber = parseInt(txtNumber.value) + 1;
if(newNumber > character.Limits[stat].max) return;
var BonusVal = document.getElementById(character["Bonus"]);
if(BonusVal.value == 0) return;
var newBonus = parseInt(BonusVal.value) - 1;
BonusVal.value = newBonus;
txtNumber.value = newNumber;
}
function subtract(e, character, stat)
{
e.preventDefault();
var txtNumber = document.getElementById(character[stat]);
var newNumber = parseInt(txtNumber.value) - 1;
if(newNumber < character.Limits[stat].min) return;
var BonusVal = document.getElementById(character["Bonus"]);
var newBonus = parseInt(BonusVal.value) + 1;
BonusVal.value = newBonus;
txtNumber.value = newNumber;
}
</script>
</head>
<body>
<table cellpadding='5' border='1' style="text-align:center; color:#ffffff; background-color:#444444; font-family:arial; font-size:14px">
<tr>
<td><b>Character</b></td>
<td><b>Strength</b></td>
<td><b>Spending Bonus</b></td>
</tr>
<tr>
<td>Alexander</td>
<td>
<input
id="AlexanderStrengthVal"
type="text" value="60"
style="width:30px; border:none; color:#ffffff; background-color:transparent; text-align:center"
onfocus="this.blur()"
onClick="add(Alexander, 'Strength')"
onContextMenu="subtract(event, Alexander, 'Strength');"
/>
</td>
<td>
<input
id="AlexanderRemainingBonusVal"
type="text"
value="30"
style="width:30px; border:none; color:#ffffff; background-color:transparent; text-align:center"
/>
</td>
</tr>
</table>
</body>
</html>
最佳答案
如何将使用 .setTimeout()
、.setInterval()
的计时器函数附加到 .onmousedown
、.onmouseup
, .onmouseout
钩子(Hook),你尝试过这种方法吗?
或者尝试一下我用于类似任务的这个随时可用的功能。 fiddle .
//
// #Timer
//
// if you are unfamiliar with this code construct,
// ( I think it is called 'module' pattern IIRC )
// this is base structure behind it:
//
// defines/runs/sets_context/passes_arguments of anonymous function in one go
// makes 'safe' ( private ) scope for module definition
// module assignment is performed at the top
// where it is easy to spot, rename, and shift around where needed
// 'factory' is a function that is supposed to return whatever the 'module' is
// be it a function, object, or whatever,
// and to assign it to arbitrary 'host' object,
// providing room to rename it in case of naming collisions
//
// ;(( function ( name, factory ) {
//
// // this === module's context
//
// this[name] = factory();
//
// } ).call(
//
// hostObject, // object to attach module to
// "customModuleName", // arbitrary name to use for it
// function () { // factory method that is supposed to define/return ( preferably independent ) piece of functionality
//
// // save to do whatever is required in this scope
// // without the impact on globals.
// // declare identifiers, etc.
// // whatever this function returns is assigned to context above
//
// function doStuff () {
// return Math.random() > .5;
// }
//
// var
// _api =
// {
// props : 1,
// methods : function () {
// var stuff;
// stuff = doStuff();
// return stuff;
// }
// };
//
// // ...code
//
// // and return whatever the module's goal is
// return _api;
//
// }
//
// ));
//
;(( function ( field, dfn ) {
// add 'Timer' identifier to global scope
this[field] = dfn();
} ).call(
window, // object to asign function to
"Timer", // property name to use
function () {
// helpers and
// shortcuts for use by code bellow
var undef; // === undefined
var aproto = Array.prototype;
var _ = {
// used to filter functions in timer api arguments
isfn : function ( o ) {
return typeof o == "function";
},
// is provided parameter an object
isobj : function ( o ) {
return o === Object( o );
},
// checks provided parameter,
// returns false for: null, undefined, NaN
// used to check if parameter is passed to timer methods
isvalid : function ( o ) {
return ( o != null ) && ( o === o );
},
// removes array elements that match passed arguments
// supposed to be used through .call/.apply function method:
// _.gc.call( arr, "a", "b", "c" ), etc.
// iterates array backward, '.splice-ing' it by 1 if current value
// matches one of provided arguments
// returns gc-ed array
// used by .off() method to remove scheduled function(s)
gc : function () {
// this === ( array ) target_array_to_cleanup
// provided arguments[] to remove
var togc = _.slice( arguments );
for (
var i = this.length;
--i >= 0;
( togc.indexOf( this[i] ) != -1 )
&& this.splice( i, 1 )
);
return this;
},
// empties passed array and returns it
// used by .off() method to remove scheduled functions
empty : function ( arr ) {
return ( arr.length = 0, arr );
},
// loops array
// uses native .forEach if available
// otherwise simulates the behaviour
// returns iterated array
// used by .fire() method to loop through registered function[] and
// to execute them in order
arreach : ( function () {
return ( typeof aproto.forEach == "function" )
? function ( arr, fn ) {
arr.forEach( fn );
return arr;
}
: function ( arr, fn ) {
for (
var i = 0,
l = arr.length;
i < l;
( i in arr )
&& fn.call( this, arr[i], i, arr ),
i++
);
return arr;
};
} )(),
// substitues content of array ( arr )
// with provided array's content ( arrnew )
// returns modified array ( arr )
// used by .start() method to quickly switch timer handler arguments
// if any are passed to it
arrsub : function ( arr, arrnew ) {
return ( aproto.push.apply( _.empty( arr ), arrnew ), arr );
},
// loops own properies of an object and retuns it
// used by .off() method, ant _.init() function
// to perform appropriate tasks ( object cleanup/property_assignment )
owneach : function ( obj, fn ) {
for (
var l in obj
) {
_.owns( obj, l )
&& fn.call( obj, l, obj[l] );
}
return obj;
},
// asyns a function
// returns new function based on provided one
// that will run asyncrounously
// used to async 'tick' handlers
async : function ( fn ) {
return function () {
var host = this;
var args = _.slice( arguments );
var origfn = fn;
setTimeout(
function () {
origfn.apply( host, args );
}
);
return this;
};
},
// asigns properties of an object ( propsObj )
// to provided ( obj ) object
// used in couple of places to quickly assign properties/values to objects
init : function ( obj, propsObj ) {
_.owneach(
propsObj,
function ( field, value ) {
obj[field] = value;
}
);
return obj;
},
// core {}.hasOwnProperty shortcut
owns : function ( obj, field ) {
return Object( obj ).hasOwnProperty( field );
},
// native [].slice shortcut
// used to turn dynamic arguments[] to real array
slice : function ( args, m, n ) {
return aproto.slice.call( args, m, n );
},
// empties an object
// used by .off() method to empty evHandler functions cache
vacate : function ( obj ) {
for (
var l in obj
) {
try {
_.owns( Object.prototype, l )
|| ( delete obj[l] );
} catch( xc ) {}
}
return obj;
}
};
// main function uses this strings
// for subscribing/removing/executing handlers
var timerEvent = {
start : "tickStart",
stop : "tickStop",
tick : "tick",
end : "tickEnd"
};
return (function ( listener ) {
// main timer function
// @param1, float, optional, how often to fire 'tick' events, default == 1000, ( == 1sec )
// @param2, integer, optional, how many times to fire 'tick' event, default == Infinity
// returns, Object, object with following api:
//
// registering functions for 'timerEvent' events:
//
// .on( evType, func )
// # caches a function for given event type ( of 'timerEvent' object )
// .off( [ evType, func] )
// # unregisteres function for given event type
// # if no function is provided removes all functions registered for event 'evType'
// # if nothing is provided removes all registered functions
// .fire( evType [, ...params_for_registered_handlers ] )
// # runs functions registered for given event type
// # passing provided arguments to them, if any
// # used internaly when .start() method is called
//
// these are for controling timer object:
//
// .start([ ...params])
// # starts triggering 'tick' events updating internal state
// # passes provided parameters to triggerd functions,
// # ( available through .data property of object passed to handlers )
// .stop()
// # pauses triggering 'tick' events ( if Timer object is in 'running state' )
// # triggers 'tickStop' event
// .reset()
// # nulls internal state, stops dispatching 'ticks', resets counter
// # triggers 'tickEnd' event
//
// these are for quering internal timer state:
//
// .currentCount()
// # how many times Timer fired so far
// # returns, integer
// .delay()
// # gives timer's delay
// # returns, float
// .repeatCount()
// # how many times timer will dispatch 'tick' events
// # returns, integer
// .running()
// # 'is running' state
// # returns, boolean
//
return function ( delay, fireCount ) {
return (function ( delay, fireCount ) {
// preconfigured object that will handle 'tick' events
var host = this;
// timer object's internal state
// used/updated by timer
var timerState =
{
currentCount : 0,
delay : Math.abs( parseFloat(delay) ) || 1000,
repeatCount : Math.abs( parseInt(fireCount) ) || Infinity,
running : false,
interval : undef
};
// hack to reset .currentCount property asynchronously in .reset() method
// without using it this way, ( by zeroing it directly, like: timerState.currentCount = 0 )
// will make last 'tick' function call report: .currentCount() == 0,
// instead of whatever the currentCount was
// at the time the 'last tick' dispatch was performed
//
// because the handlers are runned asyncronously, and
// because setting currentCount to 0 manualy ( synchronously )
// will reset it before last function gets to be runned
// reseting it asyncronously schedules a function to reset a property
// making 'last tick' function report correct currentCount ( not 0 ).
var zer0CurrentCount =
_.async(
function () {
timerState.currentCount = 0;
}
);
// holds arguments passed to last .start() call
// uses these for further .start() calls if no new arguments are given
// passes them to triggered functions
var fireargs = [];
// attaches timer api
// ( .start, .stop, .reset, .currentCount, .delay, .repeatCount, .running )
// to timer object
_.init(
host,
{
// handles starting event dispatch
// if arguments are given, caches and
// uses them for further calls
// 'keeps an eye' on timer's configuration options
// updating/aborting dispatch when/if necessary
// triggering corresponding events and functions
// does nothing if timer is already in 'active' state
start: function () {
var startargs;
host.running()
|| (
timerState.running = true,
( startargs = _.slice( arguments ) ).length
&& _.arrsub( fireargs, startargs ),
host.fire.apply(
host,
[timerEvent.start]
.concat( fireargs )
),
timerState.currentCount += 1,
host.fire.apply(
host,
[timerEvent.tick]
.concat( fireargs )
),
( timerState.currentCount == timerState.repeatCount )
&& host.reset()
|| (
timerState.interval =
setInterval(
function () {
timerState.currentCount += 1;
host.fire.apply(
host,
[timerEvent.tick]
.concat( fireargs )
);
( timerState.currentCount >= timerState.repeatCount )
&& host.reset();
},
timerState.delay
)
)
);
return host;
},
// pauses running functions ( if timer{} is in 'running' state )
// fires 'tickStop' event
// passes arguments ( given in .start call ) to cached functions
// updates timer's internal state
stop: function () {
host.running()
&& (
( timerState.interval !== undef )
&& (
clearInterval( timerState.interval ),
timerState.interval = undef
),
timerState.running = false,
host.fire.apply(
host,
[timerEvent.stop]
.concat(fireargs)
)
);
return host;
},
// cancels event dispatch
// nulls internal state
// fires 'tickEnd' functions
reset: function () {
( timerState.interval !== undef )
&& (
clearInterval( timerState.interval ),
timerState.interval = undef
);
timerState.running = false;
host.fire.apply(
host,
[timerEvent.end]
.concat( fireargs )
);
zer0CurrentCount();
return host;
},
// query timer's current state:
currentCount: function () {
return timerState.currentCount;
},
delay: function () {
return timerState.delay;
},
repeatCount: function () {
return timerState.repeatCount;
},
running: function () {
return timerState.running;
}
}
);
return host;
}).call( listener( {} ), delay, fireCount );
}
})(
// function to configure an object to handle custom events
// gives basic event handling functionality to provided object
// attaches .on/.off/.fire methods to it,
// used by main Timer function
// ( to generate base objects for handling timer events )
// passed as single ( private ) argument to code above
function ( obj ) {
if (
_.isobj(obj)
) {
// evHandler parameter object is used to store provided handlers in
(function ( evHandlers ) {
// plain object to configure for custom event handling
var host = this;
// attaches api ( .on, .off, .fire ) to provided object
_.init(
host,
{
// if function is provided cache it in 'evHandlers' object
// ( to be called when needed )
// both, event type and function argument, are required
on: function ( evtype, fn ) {
if (
_.isvalid( evtype )
&& _.isfn( fn )
) {
_.owns( evHandlers, evtype )
&& evHandlers[evtype].push( fn )
|| ( evHandlers[evtype] = [fn] );
}
return host;
},
// deletes a function ( registered for evtype ) from evHandlers{}
// both parameters are optional
off: function ( evtype, fn ) {
if (
_.isvalid( evtype )
) {
if (
_.owns( evHandlers, evtype )
) {
_.isfn( fn )
&& (
_.gc.call( evHandlers[evtype], fn ),
evHandlers[evtype].length
|| ( delete evHandlers[evtype] ), 1
)
|| (
_.empty( evHandlers[evtype] ),
delete evHandlers[evtype]
);
}
} else {
_.owneach(
evHandlers,
function ( evtype, fns ) {
_.empty( fns );
}
);
_.vacate( evHandlers );
}
return host;
},
// triggers functions registered for ( string ) evtype event
// passes 'event{}' to handlers
// it holds event type ( .type ),
// data[] ( .data ) provided through .fire call,
// object through which method is called ( .target )
// and current execting function ( .handler )
// runs handlers asynchronusly by passing them to
// _.async() method before execution
fire: function ( evtype ) { // ( any )...args
if (
_.isvalid( evtype )
) {
if (
_.owns( evHandlers, evtype )
) {
var fireargs = _.slice( arguments, 1 );
_.arreach(
evHandlers[evtype],
function ( evhandler ) {
_.async( evhandler ).call(
host,
{
type : evtype,
data : fireargs,
target : host,
handler : evhandler
}
);
}
);
}
}
return host;
}
}
);
}).call(
obj, // passed object to apply event handling functionality to
{} // plain object to cache registered functions in
);
}
// gives back passed/configued object
return obj;
}
);
}
));
//
// use:
//
// set event dispatch frequency 2x/sec
// run it 5x ( skip second argument to run functions indefinitely )
// check out the console
var timerObj = Timer( 1000 / 2, 5 );
// shortcut function to start the timer
function goTimer () {
// start 'ticking' functions,
// pass arbitrary arguments to handlers
timerObj.start(
Math.random(),
( new Date ).valueOf()
);
}
// register functions for 'tick' cycle
timerObj
.on(
"tickStart",
function ( e ) {
console.clear();
console.log(
e.type + ", \n",
( new Date ).valueOf()
);
}
)
.on(
"tick",
function ( e ) {
// updateStuff();
console.log(
e.type + "#1, "
, "#", this.currentCount(),", "
, e.data
);
}
)
.on(
"tick",
function ( e ) {
// updateStuff();
console.log(
e.type + "#2, "
, "Math.random() < Math.random(): "
, Math.random() < Math.random()
);
}
)
.on(
"tickEnd",
function ( e ) {
console.log(
e.type + ", \n"
, "e.target === this: "
, e.target === this
, ", e.target === timerObj: "
, e.target === timerObj
, "."
);
setTimeout( goTimer, 10000 * Math.random() );
}
);
//
setTimeout( goTimer, 2000 );
//
//
//
//
关于javascript - 合并 OnMouseUp/Down 功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19409507/
我已经在 mouseUp 上设置了事件监听器。 我想在短时间内(只需单击)onmouseUp 和按住后的 onmouseUp 之间进行区分,让我们说超过一秒或 onmouseDown 与 mouseM
我有几个全局变量被设置为 $(this)在小 1 或 2 按钮的 mouseup 上。基于 mouseup 上全局变量的比较,我的代码应该做一些事情。当我在 Firebug 中单步执行代码时,变量被设
我正在开发一个 tilemap 构造器应用程序,它使用类似绘画的功能来选择一个图 block (来自图像元素的 src)并使用 mouseup 和 mousedown 绘制它事件处理程序。 无论出于何
我有一个包含 IFrame 的文档(所有源项目都来自同一个域),当我将 onmouseup 事件附加到我的 IFrame 中的一个 div 时,它会在我的鼠标抬起时触发,无论我是否还在我光标所在的元素
我有一个矩形,我正在尝试使用 javascript 移动它。我可以使用函数让它左右移动,但是当我按住鼠标时它不会继续移动。这是我的 html 代码: LEFT RIGHT 这是我的 JavaScrip
我有一个working tool (请参阅第一个代码块),我想在其中包含单击并按住功能。 我想在按住左按钮时快速加,在按住右按钮时快速减。就像它已经具有的单击功能一样,但是是一个更快的选项。 我是一个
我在 Delphi 7 中的 TStringGrid 有一个奇怪的行为。如果弹出菜单与网格关联,Delphi 不会调用 OnMouseUp 事件。基本上,当按下人民币时,菜单的弹出会以某种方式取消/延
我有一个矩形,我正在尝试使用 javascript 移动它。我可以使用函数让它左右移动,但是当我按住鼠标时它不会继续移动。这是我的 html 代码: LEFT RIGHT 这是我的 JavaScrip
我创建了一个简单的 JS slider ,它对 eventListener 的点击使用react onmousedown .但是如果你运行下面的代码,你会看到,toddler没有被 eventList
我想在不删除选项的情况下删除选择。代码如下所示: item 1 如果我在 HTML 中添加一个链接: Remove selection 并且使用 jQuery 一切正常: $('.r
我需要一些帮助: 当我点击最后一个 h2 元素时,我试图移动到另一个页面,但发生的情况是它正在处理所有 h2 元素。 事情是这样的: function ini(){ docu
我有以下 html 结构: high light me with mouse!! highlight me with mouse
我有一个问题,我还没有找到答案。 当我使用此方法捕获鼠标松开事件时: 这是否比这种新方法更有效: document.getElementById("Id").addEventListener("
我构建了一个 javascript 应用程序,用于在同一页面中将 div 从一个地方拖放到另一个地方。我已经制作了拖动部分。我有 div 的坐标,我必须在其中放下 div,但我被困在应该引入条件以匹配
我有一个 div,其中设置了一个 onMouseUp 事件(在 HTML 中)。在该 div 中有许多元素,其中一些包含我想要拖动的 handle 图标。图标有一个 onMouseDown 事件。 当
我使用 onmousedown 事件创建了一个按钮,单击该事件时会循环播放音轨。我试图在单击同一按钮时结束音频循环。我尝试过 onmouseup 事件,但没有运气,有什么想法吗? (我是 JavaSc
我在 JSP 中重构一些 html,我注意到代码有一个按钮的多个 onmouseup 属性。 这是有效的 html 吗,它似乎有效,但它是否有效? 最佳答案 Yes ,您可以有多个事件监听器,不,使用
这是我从 w3schools 获得的示例,我在其中单独使用 safari 浏览器时会出现奇怪的行为。 http://www.w3schools.com/jsref/tryit.asp?filename
我有一个 slider 组件,它应该在鼠标抬起后停止移动。我浏览过论坛,我的代码与 here 非常相似 const Slider = ({ mainColour }) => { const [cu
我只是想问一下在部署时触摸屏移动设备是否支持 onmouseup 和 onmousedown 事件。 我这里有这段代码: 而且我不确定该设备是否支持这些。 我无法测试它,因为我还没有设备。如果不是,
我是一名优秀的程序员,十分优秀!