我只是尝试在这个JavaScript代码中添加代码,以获取幻灯片的值并将其传递到input type="hidden"中,但我无法将值传递到input type="hidden"中,我做错了什么?不管怎样,感谢您的帮助!
以下是JavaScript代码:
// <![CDATA[
var hWidth, bWidth;
function setBgPos(v) {
var off = v * hWidth;
var pos = -bWidth + (v * bWidth);
$('slider').setStyle({backgroundPosition: Math.round(pos - off) + 'px'});
}
function setSlideOutput(v) {
$('percent').innerHTML = Math.round(v * 100) + '%';
}
Event.observe(window, 'load', function() {
hWidth = $('slider-handle').getWidth();
bWidth = $('slider-bar').getWidth();
var slide = new Control.Slider('slider-handle', 'slider-bar', {
sliderValue: 0.25,
onSlide:
function(v) {
setBgPos(v);
setSlideOutput(v);
$('percentage').value = Math.round(v * 100) + '%';
},
onChange:
function(v) {
setBgPos(v);
setSlideOutput(v);
$('percentage').value = Math.round(v * 100) + '%';
}
});
setBgPos(slide.value);
setSlideOutput(slide.value);
});
// ]]>
HTML:
<!DOCTYPE html>
<html lang="nl">
<head>
<script src="//ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0/scriptaculous.js"></script>
<style>
#slider, #slider-bar, #slider-handle {
border: 0;
padding: 0;
margin: 0;
}
#slider {
width: 300px;
height:42px;
background: url(img/bg.gif) no-repeat -300px;
margin-left: 42px;
}
#slider-bar {
width:300px;
height:42px;
background: url(img/track.png) no-repeat;
}
#slider-handle {
width:42px;
height:42px;
cursor:move;
background: url(img/gripper.png) no-repeat;
}
#percent {
font-size: 75%;
font-family: arial;
font-weight: bold;
text-align: center;
padding-top: 1.1em;
}
</style>
</head>
<body>
<div id="slider">
<div id="slider-bar">
<div id="slider-handle"><p id="percent"></p></div>
</div>
</div>
<input type="hidden" id="percentage" name="percentage" value="0" />
</body>
</html>
onChange
、onSlide
事件中添加console.log()
以确认获取的值。设置元素值的另一种方法是使用setValue()
,例如$('percentage').setValue(Math.round(v * 100) + '%');
。 - Geek Num 88