Zeer eenvoudig, zeer soepel, JavaScript-selectiekader

Ik ben op zoek naar een heel eenvoudig en soepel, lichtgewicht javascript of jQuery-tent. Ik heb al silk marqueeof zoiets geprobeerd, maar het zou niet werken met de applicatie ik gebruikte. Dus hoe eenvoudiger en korter, hoe beter – en gemakkelijker te debuggen. Kent iemand een eenvoudig te implementeren javascript-vervanging voor de selectiekader?

Pastebin

Code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
var tWidth='300px';                  // width (in pixels)
var tHeight='25px';                  // height (in pixels)
var tcolour='#ffffcc';               // background colour:
var moStop=true;                     // pause on mouseover (true or false)
var fontfamily = 'arial,sans-serif'; // font for content
var tSpeed=3;                        // scroll speed (1 = slow, 5 = fast)
// enter your ticker content here (use \/ and \' in place of / and ' respectively)
var content='Are you looking for loads of useful information <a href="http:\/\/javascript.about.com\/">About Javascript<\/a>? Well now you\'ve found it.';
var cps=-tSpeed; var aw, mq; var fsz = parseInt(tHeight) - 4; function startticker(){if (document.getElementById) {var tick = '<div style="position:relative;width:'+tWidth+';height:'+tHeight+';overflow:hidden;background-color:'+tcolour+'"'; if (moStop) tick += ' onmouseover="cps=0" onmouseout="cps=-tSpeed"'; tick +='><div id="mq" style="position:absolute;right:0px;top:0px;font-family:'+fontfamily+';font-size:'+fsz+'px;white-space:nowrap;"><\/div><\/div>'; document.getElementById('ticker').innerHTML = tick; mq = document.getElementById("mq"); mq.style.right=(10+parseInt(tWidth))+"px"; mq.innerHTML='<span id="tx">'+content+'<\/span>'; aw = document.getElementById("tx").offsetWidth; lefttime=setInterval("scrollticker()",50);}} function scrollticker(){mq.style.right = (parseInt(mq.style.right)>(-10 - aw)) ?
mq.style.right = parseInt(mq.style.right)+cps+"px": parseInt(tWidth)+10+"px";} window.onload=startticker;
</script>
</head>
<body>
<div id="ticker">
    this is a simple scrolling text!
</div>
</body>
</html>

Antwoord 1, autoriteit 100%

hiya eenvoudige demovan aanbevelingen in bovenstaande opmerkingen: http://jsfiddle.net/FWWEn/

met pauzefunctionaliteit bij mouseover: http://jsfiddle.net/zrW5q/

hoop dat dit helpt, veel plezier, proost!

html

<h1>Hello World!</h1>
<h2>I'll marquee twice</h2>
<h3>I go fast!</h3>
<h4>Left to right</h4>
<h5>I'll defer that question</h5>​

Jquery-code

(function($) {
        $.fn.textWidth = function(){
             var calc = '<span style="display:none">' + $(this).text() + '</span>';
             $('body').append(calc);
             var width = $('body').find('span:last').width();
             $('body').find('span:last').remove();
            return width;
        };
        $.fn.marquee = function(args) {
            var that = $(this);
            var textWidth = that.textWidth(),
                offset = that.width(),
                width = offset,
                css = {
                    'text-indent' : that.css('text-indent'),
                    'overflow' : that.css('overflow'),
                    'white-space' : that.css('white-space')
                },
                marqueeCss = {
                    'text-indent' : width,
                    'overflow' : 'hidden',
                    'white-space' : 'nowrap'
                },
                args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false }, args),
                i = 0,
                stop = textWidth*-1,
                dfd = $.Deferred();
            function go() {
                if(!that.length) return dfd.reject();
                if(width == stop) {
                    i++;
                    if(i == args.count) {
                        that.css(css);
                        return dfd.resolve();
                    }
                    if(args.leftToRight) {
                        width = textWidth*-1;
                    } else {
                        width = offset;
                    }
                }
                that.css('text-indent', width + 'px');
                if(args.leftToRight) {
                    width++;
                } else {
                    width--;
                }
                setTimeout(go, args.speed);
            };
            if(args.leftToRight) {
                width = textWidth*-1;
                width++;
                stop = offset;
            } else {
                width--;            
            }
            that.css(marqueeCss);
            go();
            return dfd.promise();
        };
    })(jQuery);
$('h1').marquee();
$('h2').marquee({ count: 2 });
$('h3').marquee({ speed: 5 });
$('h4').marquee({ leftToRight: true });
$('h5').marquee({ count: 1, speed: 2 }).done(function() { $('h5').css('color', '#f00'); })​

Antwoord 2, autoriteit 31%

Ik heb een heel eenvoudige functie gemaakt voor selectiekader. Zie: http://jsfiddle.net/vivekw/pHNpk/2/
Het pauzeert bij mouseover & hervat met muisverlof. De snelheid kan worden gevarieerd. Makkelijk te begrijpen.

function marquee(a, b) {
var width = b.width();
var start_pos = a.width();
var end_pos = -width;
function scroll() {
    if (b.position().left <= -width) {
        b.css('left', start_pos);
        scroll();
    }
    else {
        time = (parseInt(b.position().left, 10) - end_pos) *
            (10000 / (start_pos - end_pos)); // Increase or decrease speed by changing value 10000
        b.animate({
            'left': -width
        }, time, 'linear', function() {
            scroll();
        });
    }
}
b.css({
    'width': width,
    'left': start_pos
});
scroll(a, b);
b.mouseenter(function() {     // Remove these lines
    b.stop();                 //
    b.clearQueue();           // if you don't want
});                           //
b.mouseleave(function() {     // marquee to pause
    scroll(a, b);             //
});                           // on mouse over
}
$(document).ready(function() {
    marquee($('#display'), $('#text'));  //Enter name of container element & marquee element
});

Antwoord 3, autoriteit 22%

Daar heb ik zojuist een eenvoudige jQuery-plug-in voor gemaakt. Probeer het 😉

https://github.com/aamirafridi/jQuery.Marquee


Antwoord 4, autoriteit 16%

Waarom aangepaste jQuery-code voor Marquee schrijven… gebruik gewoon een plug-in voor jQuery – marquee() en gebruik deze zoals in het onderstaande voorbeeld:

Eerst opnemen:

<script type='text/javascript' src='//cdn.jsdelivr.net/jquery.marquee/1.3.1/jquery.marquee.min.js'></script>

en dan:

//proporcional speed counter (for responsive/fluid use)
var widths = $('.marquee').width()
var duration = widths * 7;
$('.marquee').marquee({
    //speed in milliseconds of the marquee
    duration: duration, // for responsive/fluid use
    //duration: 8000, // for fixed container
    //gap in pixels between the tickers
    gap: $('.marquee').width(),
    //time in milliseconds before the marquee will start animating
    delayBeforeStart: 0,
    //'left' or 'right'
    direction: 'left',
    //true or false - should the marquee be duplicated to show an effect of continues flow
    duplicated: true
});

Als je het eenvoudiger en beter kunt maken, daag ik jullie allemaal uit :). Maak je leven niet moeilijker dan het zou moeten zijn. Meer over deze plug-in en zijn functionaliteiten op: http://aamirafridi.com/jquery/jquery-marquee -plug-in


Antwoord 5, autoriteit 13%

De volgende werken:

http://jsfiddle.net/xAGRJ/4/

Het probleem met je originele code was dat je scrollticker()aanroept door een string door te geven aan setInterval, waar je gewoon de functienaam moet doorgeven en deze moet behandelen als een variabele:

lefttime = setInterval(scrollticker, 50);

in plaats van

lefttime = setInterval("scrollticker()", 50);

Antwoord 6, autoriteit 4%

Ik heb mijn eigen versie gemaakt, gebaseerd op de code hierboven gepresenteerd door @Tats_innit .
Het verschil is de pauzefunctie. Werkt in dat opzicht iets beter.

(function ($) {
var timeVar, width=0;
$.fn.textWidth = function () {
    var calc = '<span style="display:none">' + $(this).text() + '</span>';
    $('body').append(calc);
    var width = $('body').find('span:last').width();
    $('body').find('span:last').remove();
    return width;
};
$.fn.marquee = function (args) {
    var that = $(this);
    if (width == 0) { width = that.width(); };
    var textWidth = that.textWidth(), offset = that.width(), i = 0, stop = textWidth * -1, dfd = $.Deferred(),
        css = {
            'text-indent': that.css('text-indent'),
            'overflow': that.css('overflow'),
            'white-space': that.css('white-space')
        },
        marqueeCss = {
            'text-indent': width,
            'overflow': 'hidden',
            'white-space': 'nowrap'
        },
        args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false, pause: false }, args);
    function go() {
        if (!that.length) return dfd.reject();
        if (width <= stop) {
            i++;
            if (i <= args.count) {
                that.css(css);
                return dfd.resolve();
            }
            if (args.leftToRight) {
                width = textWidth * -1;
            } else {
                width = offset;
            }
        }
        that.css('text-indent', width + 'px');
        if (args.leftToRight) {
            width++;
        } else {
            width=width-2;
        }
        if (args.pause == false) { timeVar = setTimeout(function () { go() }, args.speed); };
        if (args.pause == true) { clearTimeout(timeVar); };
    };
    if (args.leftToRight) {
        width = textWidth * -1;
        width++;
        stop = offset;
    } else {
        width--;
    }
    that.css(marqueeCss);
    timeVar = setTimeout(function () { go() }, 100);
    return dfd.promise();
};
})(jQuery);

gebruik:

om te beginnen: $(‘#Text1’).marquee()

pauze: $(‘#Text1’).marquee({ pause: true })

resume: $(‘#Text1’).marquee({ pause: false })


Antwoord 7, autoriteit 2%

Mijn tekstkader voor meer tekst,
en positie absoluut ingeschakeld

http://jsfiddle.net/zrW5q/2075/

(function($) {
$.fn.textWidth = function() {
var calc = document.createElement('span');
$(calc).text($(this).text());
$(calc).css({
  position: 'absolute',
  visibility: 'hidden',
  height: 'auto',
  width: 'auto',
  'white-space': 'nowrap'
});
$('body').append(calc);
var width = $(calc).width();
$(calc).remove();
return width;
};
$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
    offset = that.width(),
    width = offset,
    css = {
        'text-indent': that.css('text-indent'),
        'overflow': that.css('overflow'),
        'white-space': that.css('white-space')
    },
    marqueeCss = {
        'text-indent': width,
        'overflow': 'hidden',
        'white-space': 'nowrap'
    },
    args = $.extend(true, {
        count: -1,
        speed: 1e1,
        leftToRight: false
    }, args),
    i = 0,
    stop = textWidth * -1,
    dfd = $.Deferred();
function go() {
    if (that.css('overflow') != "hidden") {
        that.css('text-indent', width + 'px');
        return false;
    }
    if (!that.length) return dfd.reject();
    if (width <= stop) {
        i++;
        if (i == args.count) {
            that.css(css);
            return dfd.resolve();
        }
        if (args.leftToRight) {
            width = textWidth * -1;
        } else {
            width = offset;
        }
    }
    that.css('text-indent', width + 'px');
    if (args.leftToRight) {
        width++;
    } else {
        width--;
    }
    setTimeout(go, args.speed);
};
if (args.leftToRight) {
    width = textWidth * -1;
    width++;
    stop = offset;
} else {
    width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
// $('h1').marquee();
$("h1").marquee();
$("h1").mouseover(function () {     
    $(this).removeAttr("style");
}).mouseout(function () {
    $(this).marquee();
});
})(jQuery);

Antwoord 8, autoriteit 2%

Responsieve weerstand jQuery selectiekader eenvoudige plug-in. Zelfstudie:

// start plugin
    (function($){
        $.fn.marque = function(options, callback){
            // check callback
            if(typeof callback == 'function'){
                callback.call(this);
            } else{
                console.log("second argument (callback) is not a function");
                // throw "callback must be a function"; //only if callback for some reason is required
                // return this; //only if callback for some reason is required
            }
            //set and overwrite default functions
            var defOptions = $.extend({
                speedPixelsInOneSecound: 150, //speed will behave same for different screen where duration will be different for each size of the screen
                select: $('.message div'),
                clickSelect: '', // selector that on click will redirect user ... (optional)
                clickUrl: '' //... to this url. (optional)
            }, options);
            //Run marque plugin
            var windowWidth = $(window).width();
            var textWidth = defOptions.select.outerWidth();
            var duration = (windowWidth + textWidth) * 1000 / defOptions.speedPixelsInOneSecound;
            var startingPosition = (windowWidth + textWidth);
            var curentPosition = (windowWidth + textWidth);
            var speedProportionToLocation = curentPosition / startingPosition;
            defOptions.select.css({'right': -(textWidth)});
            defOptions.select.show();
            var animation;
            function marquee(animation){
                curentPosition = (windowWidth + defOptions.select.outerWidth());
                speedProportionToLocation = curentPosition / startingPosition;
                animation = defOptions.select.animate({'right': windowWidth+'px'}, duration * speedProportionToLocation, "linear", function(){
                     defOptions.select.css({'right': -(textWidth)});
                });
            }
            var play = setInterval(marquee, 200);
            //add onclick behaviour
            if(defOptions.clickSelect != '' && defOptions.clickUrl != ''){
                defOptions.clickSelect.click(function(){
                    window.location.href = defOptions.clickUrl;
                });
            }
            return this;
        };
    }(jQuery)); 
// end plugin 

Gebruik deze aangepaste jQuery-plug-in zoals hieronder:

//use example
$(window).marque({
    speedPixelsInOneSecound: 150, // spped pixels/secound
    select: $('.message div'), // select an object on which you want to apply marquee effects.
    clickSelect: $('.message'), // select clicable object (optional)
    clickUrl: 'services.php' // define redirection url (optional)
});

Other episodes