通过滑块循环

时间:2016-08-26 19:57:12

标签: javascript jquery html css slider

首先是link

我正在尝试创建一个滑块,在滑块完成循环后,我无法显示第一张幻灯片。我希望滑块在连续循环中显示所有滑块而不会有任何中断。

HTML代码:

<div class="main-container">
    <div class="main-slider">
        <div id="mydiv">    
        </div>
    </div>
</div>

在div'#mydiv'中添加了滑块。

JS代码:

$(document).ready(function() {
var screenHeight = $(window).height();
var screenWidth = $(document).width();

$(".main-slider").css("height", screenHeight + 4);


var imageURLS = [
    "http://images6.fanpop.com/image/photos/36800000/Beautiful-Landscapes-image-beautiful-landscapes-36803145-1920-1080.jpg",
    "http://www.cnmuqi.com/data/out/222/images-of-landscapes-7409399.jpeg",
    "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcS5cXFv_tmqWQFHllbUOvL9reoqTB9jQLWc-16Sj_r2vKPhNqobaQ",
    "http://www.ucreative.com/wp-content/uploads/2014/11/Landscape-Photography-Banner1.jpg",
    "http://www.qqxxzx.com/images/images-of-landscapes/images-of-landscapes-8.jpg",
    "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRNO6NIwG_n-pFppB_-DFN3Pt5M-sWe_-CMxR6MDz3eV9i38bA2",
    "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTyer4s2_wLSkH86aSggqXv5nXU6z6pQC_RNGYEcIgjuQAESwtG",
    "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSwQAHl6_-8GpV7c86T_qSSWlF6bsyyl4JoYVh4flC2dcZDiZGL"

];

$.each(imageURLS, function(k, v) {
    $('#mydiv').append('<div class="image_block"><img  src="' + v + '" /></div>');
});

$(".image_block img").css("width", screenWidth);
$(".image_block img").css("height", screenHeight);

function initial_call() {

    $('.image_block img').eq(0).attr('src', imageURLS[0]);
    $('.image_block img').eq(1).attr('src', imageURLS[1]);
}
//  initial_call();
var count = 1;
setInterval(function() {

    translate_value = count * screenHeight + count * 4;
    $("#mydiv").css("transform", "translate(0px,-" + translate_value + "px)");

    count++;
}, 2000);




}); //end of $(document).ready();

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

您只需添加以下行:

count++;
count%=imageURLS.length;

计数将继续增加,但一旦到达结束时再进行包装。

工作example

答案 1 :(得分:1)

我添加 using System; using System.Linq; using System.Media; using System.Xml.Linq; using System.Collections.Generic; using System.Text; using WMPLib; using AxWMPLib; namespace Memory { /// <summary> /// this handles the creation, tracking, and scoring of a single session /// </summary> class Session { #region class Vars/Properties File save; ItemsPool _all, _presented, _selected, _displayed; initVars Vars = initVars.defaults; sessTimer _timer; System.Timers.Timer onset; bool p_onset = false; string _output = "Memdata." + DateTime.Now.ToString("Mdyy-HHmm") + ".txt"; int _sessCount = 0; AxWindowsMediaPlayer axWindowsMediaPlayer1; /// <summary> /// a collection of the sum of the scores for this session /// </summary> List<int[]> ScoreSum; /// <summary> /// the Sum of time results /// </summary> int TimesSum = 0; /// <summary> /// the number of items to display /// </summary> int _itemCount; /// <summary> /// the number of items to display /// </summary> public int itemCount { get { return _itemCount; } set { _itemCount = value; } } /// <summary> /// the session count /// </summary> public int SessionCount { get { return _sessCount; } } string _prefix = ""; /// <summary> /// the prefix for the Rows /// </summary> public string RowPrefix { get { return _prefix; } set { _prefix = value; } } /// <summary> /// the image width for each item /// </summary> public int ImgWidth { get; set; } ///<summary> ///video width for each item /// </summary> public int VidWidth { get; set; } /// <summary> /// the max runs for this session /// </summary> public int maxRuns { get; set; } /// <summary> /// debug value /// </summary> public bool debug { get { return Vars.debug; } } /// <summary> /// the onset value /// </summary> public int onsetValue { get { return Vars.onset; } } /// <summary> /// view Images before Audio /// </summary> public bool ViewImages { get { return Vars.ViewImages; } } /// <summary> /// allow correction /// </summary> public bool AllowCorrection { get { return Vars.allowCorrection; } } /// <summary> /// play sounds one at a time /// </summary> public bool playOne { get { return Vars.playOne; } } #endregion #region constructors /// <summary> /// create a new session and load settings from an XML string or file /// </summary> /// <param name="xml">either a path or a string of XML</param> /// <param name="SaveName">the name of the output file</param> public Session(string xml, string output, bool makeUnique) { if (output != "") { _output = output; } save = new File(_output); if (makeUnique) { save.MakeUnique(); } XDocument setupXML; //check to see if there are any XML nodes ie. is this a string of XML, or a path string fchar = xml.Substring(0, 1); if (fchar == "<") { setupXML = XDocument.Parse(xml); } else { setupXML = XDocument.Load(xml); } LoadXML(setupXML); //set some class vars based on the initial vars //these are variables that may change during the session _itemCount = Vars.Columns; ScoreSum = new List<int[]>(); ImgWidth = Vars.width; maxRuns = Vars.maxRuns; _presented = new ItemsPool(); _selected = new ItemsPool(); _timer = new sessTimer(); _timer.Update += new EventHandler<StringEventArgs>(_timer_Update); } void LoadXML(XDocument setupXML) { // get the initial variables var initVars = from feed in setupXML.Descendants("var") select new { Name = feed.Attribute("Name").Value, Value = feed.Value }; foreach (var feed in initVars) { Vars.SetVar(feed.Name, feed.Value); } // parse the image and audio filename var ifiles = from feed in setupXML.Descendants("stim") select new Item { Name = feed.Attribute("Name").Value, video = feed.Element("video").Value, image = feed.Element("image").Value }; _all = new ItemsPool(); foreach (Item it in ifiles) { _all.add(Item.getItem(it.Name , Vars.ImageDirectory + it.image , Vars.VideoDirectory + it.video )); } } #endregion #region public methods /// <summary> /// randomly generate an items pool for playback /// </summary> /// <returns></returns> public ItemsPool RandPresentation() { _presented = new ItemsPool(); _presented = RandPool(_itemCount, _all); if (Vars.Randomize) { _displayed = new ItemsPool(); _displayed = RandPool(_itemCount, _presented); } else { _displayed = _presented; } return _displayed; } ItemsPool RandPool(int count, ItemsPool pool) { ItemsPool rp = new ItemsPool(); Item it = RandItem(pool); //get new randoms until we have enough do { //since only unique items may be added to an ItemPool, //we don't need to check if the the pool contains the random item it = RandItem(pool); rp.add(it); } while (rp.count < count); return rp; } /// <summary> /// clear all, and start a new session /// </summary> public void startNew() { if (_timer.Active) { stopTimer(); } _sessCount++; _selected = new ItemsPool(); } /// <summary> /// decrement the session count /// </summary> public void decSessCount() { if (_sessCount > 0) { _sessCount--; } } /// <summary> /// log the results to the save file /// </summary> public void LogResults() { if (_sessCount > 0) { logResults(); } } /// <summary> /// add an item to the selected pool. /// </summary> /// <param name="it"></param> public void Selected(Item it) { _selected.add(it); if (_selected.count == _itemCount) { stopTimer(); LogResults(); } } private void stopTimer() { _timer.stop(); timerStopped(this, new EventArgs()); } /// <summary> /// remove an item from the selected pool /// </summary> /// <param name="it"></param> public void remove(Item it) { if (_selected.Contains(it)) { _selected.remove(it); } } public void logSummary() { string[] lineSC = new string[_itemCount + 3]; string lineF = "\t\t{0}\t{1}"; string sumHdr1 = "\t\tPart\tN"; if (RowPrefix.Length > 7) { lineF = "\t{0}\t{1}"; sumHdr1 = "\tPart\t\tN"; } lineSC[0] = String.Format(lineF, RowPrefix, _sessCount.ToString()); int ItemSum = 0; //go through each column, get the sum for (int i = 0; i < _itemCount; i++) { int cSum = 0; //go through the list and get the score results for this column foreach (int[] iarr in ScoreSum) { cSum += iarr[i]; } ItemSum += cSum; lineSC[i + 1] = cSum.ToString(); } //Mean Time //Same as original code //Mean Sum //same as original code //Sum lineSC[_itemCount + 2] = ItemSum.ToString(); //create the header string[] sumHdr = new string[_itemCount + 2]; sumHdr[0] = sumHdr1; for (int i = 0; i < _itemCount; i++) { sumHdr[i + 1] = "Itm" + (i + 1).ToString(); } sumHdr[_itemCount + 1] = "M_Time\tSum"; //put to file save.Append(dashBreak()); save.Append(sumHdr); save.Append(lineSC); save.Append(dashBreak()); } string dashBreak() { StringBuilder sb = new StringBuilder("|--------"); for (int i = 0; i < _itemCount + 3; i++) { sb.Append("--------"); if (i == _itemCount + 2) { sb.Append("-----------|"); } } return sb.ToString(); } #endregion #region private methods /// <summary> /// save the session's results to a text file /// </summary> void logResults() { //there should be a scoring method here and perhaps an option to //output scores instead of text options, but Susan did not want that. //added scoring 5/8/09 int iCount = _presented.count; string[] score = new string[iCount + 2]; int[] scs = new int[iCount]; for (int i = 0; i < iCount; i++) { Item pre = _presented.getItem(i); Item sel = _selected.getItem(i); int sc = 1; //if (Item.Compare(pre,sel)) //{ sc = 1; } if (pre.Name == sel.Name ) { sc = 0; } score[i + 1] = sc.ToString(); scs[i] = sc; } //log for the summary ScoreSum.Add(scs); TimesSum += _timer.Time; //create array for log file score[0] = String.Format("{0}\t{1}\t{2}", RowPrefix, _sessCount.ToString(), "errs"); score[iCount + 1] = _timer.Time.ToString(); //add the presented line save.Append(MakeRow(_presented, "pres")); //add the selected line save.Append(MakeRow(_selected, "sel")); //add the score line save.Append(score); //put an extra line in there save.Append(""); } string[] MakeRow(ItemsPool ip, string prefix) { string[] row = new string[ip.count + 1]; // 2]; row[0] = String.Format("{0}\t{1}\t{2}",RowPrefix, _sessCount.ToString(), prefix); if (ip.count > 0) { for (int i = 0; i < ip.count; i++) { Item it = ip.getItem(i); row[i + 1] = it.Name; } } //row[ip.count + 1] = _timer.Time.ToString(); return row; } Item RandItem(ItemsPool pool) { //setup a new random object Random r = new Random(); /* the random generator has a fear of the last option, * so I'm giving it two chances to grab the last item... * this may need adjustment. */ int _play = r.Next(pool.count + 1); if (_play >= pool.count) { _play -= 1; } Item ri = pool.getItem(_play); return ri; } #endregion #region video player methods void playItem(Item it) { axWindowsMediaPlayer1 = new AxWindowsMediaPlayer(); axWindowsMediaPlayer1.PlayStateChange += new PlayStateChangeHandler(axWindowsMediaPlayer1_PlayStateChange); this.axWindowsMediaPlayer1.URL ="it.video"; axWindowsMediaPlayer1.Ctlcontrols.play(); } void axWindowsMediaPlayer1_LoadCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { if (p_onset) { axWindowsMediaPlayer1.Ctlcontrols.play(); } else { axWindowsMediaPlayer1.Ctlcontrols.play(); if (!Vars.playOne) { PlayNext(); } } } int playQueue = 0; new EventArgs()); } } } ...end of code block same as original 所以使用此变量,我可以检查结束点并将var finishNumber = imageHeight * imageURLS.length;设置为translate_value

0

最终守则

jQuery的:

if(translate_value == finishNumber){
    translate_value = 0;
}

HTML:

$(document).ready(function() {
var screenHeight = $(window).height();
var screenWidth = $(document).width();
var imageHeight = screenHeight;
$(".main-slider").css("height", screenHeight);

var imageURLS = [
    "http://images6.fanpop.com/image/photos/36800000/Beautiful-Landscapes-image-beautiful-landscapes-36803145-1920-1080.jpg",
    "http://www.cnmuqi.com/data/out/222/images-of-landscapes-7409399.jpeg",
    "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcS5cXFv_tmqWQFHllbUOvL9reoqTB9jQLWc-16Sj_r2vKPhNqobaQ",
    "http://www.ucreative.com/wp-content/uploads/2014/11/Landscape-Photography-Banner1.jpg",
    "http://www.qqxxzx.com/images/images-of-landscapes/images-of-landscapes-8.jpg",
    "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRNO6NIwG_n-pFppB_-DFN3Pt5M-sWe_-CMxR6MDz3eV9i38bA2",
    "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTyer4s2_wLSkH86aSggqXv5nXU6z6pQC_RNGYEcIgjuQAESwtG",
    "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSwQAHl6_-8GpV7c86T_qSSWlF6bsyyl4JoYVh4flC2dcZDiZGL"
];

$.each(imageURLS, function(k, v) {
    $('#mydiv').append('<div class="image_block"><img  src="' + v + '" /></div>');
});

$(".image_block img").css("width", screenWidth);
$(".image_block img").css("height", screenHeight);

function initial_call() {

    $('.image_block img').eq(0).attr('src', imageURLS[0]);
    $('.image_block img').eq(1).attr('src', imageURLS[1]);
}
//  initial_call();
var count = 1;
var translate_value = 0;
var finishNumber = imageHeight * imageURLS.length;
setInterval(function() {
    console.log(imageURLS.length)
    translate_value = translate_value + screenHeight;
    if(translate_value == finishNumber){
        translate_value = 0;
    }
    $("#mydiv").css("transform", "translate(0px,-" + translate_value + "px)");

    count++;
}, 2000);




}); //end of $(document).ready();

CSS:

<div class="main-container">
    <div class="main-slider">
        <div id="mydiv">    
        </div>
    </div>
</div>

工作示例:https://jsfiddle.net/81jhnb5a/2/