一般而言,我对JS / JQuery Web开发人员是相当陌生的。

对于一项工作任务,我被要求提出一个解决方案,其中显示列表中的前3个基金,如果投资了3个以上,则将显示“显示所有基金”按钮,单击该按钮将进行切换其余资金。

<!DOCTYPE html>
        <html lang="en">

        <head>
            <title>Check your retirement plan demo</title>
            <meta charset="UTF-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link rel="stylesheet" type="text/css" href="css/dropdown-component.css" />
            <script src="js/modernizr.custom.63321.js"></script>
        </head>

        <body style="background-color:#eaeaea;">

            <div class="container">
                <h2> Dropdown Component</h2>

                <!-- THIS BIT FUNDS START -->
                <section class="main clearfix">

                    <select id="cd-dropdown" name="cd-dropdown" class="cd-select">
                        <option value="-1" selected>Funds in your portfolio (3)</option>
                        <option value="1">fund1 £60,000</option>
                        <option value="2">fund 2 £40,000</option>
                        <option value="3">fund 3 £24,000</option>
                        <option value="4">View all funds &gt;</option>
                        <option value="5">Fund 5 £40,000</option>

                    </select>

                </section>
                <!-- THIS BIT FUNDS END -->

            </div>

            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
            <script type="text/javascript" src="js/jquery.dropdown.js"></script>
            <script type="text/javascript">
                $(function () {

                    $('#cd-dropdown').dropdown({
                        gutter: 5
                    });

                });

                    </script>

        </body>

        </html>`


我正在使用jquery下拉解决方案来帮助我处理资金,但没有单击大于更多资金的功能来隐藏大于3的资金并切换它们。

 /**
     * jquery.dropdown.js v1.0.0
     * http://www.codrops.com
     *
     * Licensed under the MIT license.
     * http://www.opensource.org/licenses/mit-license.php
     *
     * Copyright 2012, Codrops
     * http://www.codrops.com
     */
    ; (function ($, window, undefined) {

        'use strict';

        $.DropDown = function (options, element) {
            this.$el = $(element);
            this._init(options);
        };

        // the options
        $.DropDown.defaults = {
            speed: 300,
            easing: 'ease',
            gutter: 0,
            // initial stack effect
            stack: true,
            // delay between each option animation
            delay: 0,
            // random angle and positions for the options
            random: false,
            // rotated [right||left||false] : the options will be rotated to thr right side or left side.
            // make sure to tune the transform origin in the stylesheet
            rotated: false,
            // effect to slide in the options. value is the margin to start with
            slidingIn: false,
            onOptionSelect: function (opt) { return false; }
        };

        $.DropDown.prototype = {

            _init: function (options) {

                // options
                this.options = $.extend(true, {}, $.DropDown.defaults, options);
                this._layout();
                this._initEvents();

            },
            _layout: function () {

                var self = this;
                this.minZIndex = 1000;
                var value = this._transformSelect();
                this.opts = this.listopts.children('li');
                this.optsCount = this.opts.length;
                this.size = { width: this.dd.width(), height: this.dd.height() };

                var elName = this.$el.attr('name'), elId = this.$el.attr('id'),
                    inputName = elName !== undefined ? elName : elId !== undefined ? elId : 'cd-dropdown-' + (new Date()).getTime();

                this.inputEl = $('<input type="hidden" name="' + inputName + '" value="' + value + '"></input>').insertAfter(this.selectlabel);

                this.selectlabel.css('z-index', this.minZIndex + this.optsCount);
                this._positionOpts();
                if (Modernizr.csstransitions) {
                    setTimeout(function () { self.opts.css('transition', 'all ' + self.options.speed + 'ms ' + self.options.easing); }, 25);
                }

            },
            _transformSelect: function () {

                var optshtml = '', selectlabel = '', value = -1;
                this.$el.children('option').each(function () {

                    var $this = $(this),
                        val = isNaN($this.attr('value')) ? $this.attr('value') : Number($this.attr('value')),
                        classes = $this.attr('class'),
                        selected = $this.attr('selected'),
                        label = $this.text();

                    if (val !== -1) {
                        optshtml +=
                            classes !== undefined ?
                                '<li data-value="' + val + '"id=fundID' + val + '><span class="' + classes + '">' + label + '</span></li>' :
                                '<li data-value="' + val + '"id=fundID' + val + '><span>' + label + '</span></li>';
                    }

                    if (val > 3) {}

                    if (selected) {
                        selectlabel = label;
                        value = val;
                    }

                });

                this.listopts = $('<ul/>').append(optshtml);
                this.selectlabel = $('<span/>').append(selectlabel);
                this.dd = $('<div class="cd-dropdown"/>').append(this.selectlabel, this.listopts).insertAfter(this.$el);
                this.$el.remove();

                return value;

            },
            _positionOpts: function (anim) {

                var self = this;

                this.listopts.css('height', 'auto');
                this.opts
                    .each(function (i) {
                        $(this).css({
                            zIndex: self.minZIndex + self.optsCount - 1 - i,
                            top: self.options.slidingIn ? (i + 1) * (self.size.height + self.options.gutter) : 0,
                            left: 0,
                            marginLeft: self.options.slidingIn ? i % 2 === 0 ? self.options.slidingIn : - self.options.slidingIn : 0,
                            opacity: self.options.slidingIn ? 0 : 1,
                            transform: 'none'
                        });
                    });

                if (!this.options.slidingIn) {
                    this.opts
                        .eq(this.optsCount - 1)
                        .css({ top: this.options.stack ? 9 : 0, left: this.options.stack ? 4 : 0, width: this.options.stack ? this.size.width - 8 : this.size.width, transform: 'none' })
                        .end()
                        .eq(this.optsCount - 2)
                        .css({ top: this.options.stack ? 6 : 0, left: this.options.stack ? 2 : 0, width: this.options.stack ? this.size.width - 4 : this.size.width, transform: 'none' })
                        .end()
                        .eq(this.optsCount - 3)
                        .css({ top: this.options.stack ? 3 : 0, left: 0, transform: 'none' });
                }

            },
            _initEvents: function () {

                var self = this;

                this.selectlabel.on('mousedown.dropdown', function (event) {
                    self.opened ? self.close() : self.open();
                    return false;

                });

                this.opts.on('click.dropdown', function () {
                    if (self.opened) {
                        var opt = $(this);
                        self.options.onOptionSelect(opt);
                        self.inputEl.val(opt.data('value'));
                        self.selectlabel.html(opt.html());
                        self.close();
                    }
                });

            },
            open: function () {
                var self = this;
                this.dd.toggleClass('cd-active');
                this.listopts.css('height', (this.optsCount + 1) * (this.size.height + this.options.gutter));
                this.opts.each(function (i) {

                    $(this).css({
                        opacity: 1,
                        top: self.options.rotated ? self.size.height + self.options.gutter : (i + 1) * (self.size.height + self.options.gutter),
                        left: self.options.random ? Math.floor(Math.random() * 11 - 5) : 0,
                        width: self.size.width,
                        marginLeft: 0,
                        transform: self.options.random ?
                            'rotate(' + Math.floor(Math.random() * 11 - 5) + 'deg)' :
                            self.options.rotated ?
                                self.options.rotated === 'right' ?
                                    'rotate(-' + (i * 5) + 'deg)' :
                                    'rotate(' + (i * 5) + 'deg)'
                                : 'none',
                        transitionDelay: self.options.delay && Modernizr.csstransitions ? self.options.slidingIn ? (i * self.options.delay) + 'ms' : ((self.optsCount - 1 - i) * self.options.delay) + 'ms' : 0
                    });

                });
                this.opened = true;

            },
            close: function () {

                var self = this;
                this.dd.toggleClass('cd-active');
                if (this.options.delay && Modernizr.csstransitions) {
                    this.opts.each(function (i) {
                        $(this).css({ 'transition-delay': self.options.slidingIn ? ((self.optsCount - 1 - i) * self.options.delay) + 'ms' : (i * self.options.delay) + 'ms' });
                    });
                }
                this._positionOpts(true);
                this.opened = false;

            }

        }

        $.fn.dropdown = function (options) {
            var instance = $.data(this, 'dropdown');
            if (typeof options === 'string') {
                var args = Array.prototype.slice.call(arguments, 1);
                this.each(function () {
                    instance[options].apply(instance, args);
                });
            }
            else {
                this.each(function () {
                    instance ? instance._init() : instance = $.data(this, 'dropdown', new $.DropDown(options, this));
                });
            }
            return instance;
        };

    })(jQuery, window);'


有人可以帮助我提出快速解决方案或为我指明正确的方向吗?谢谢

最佳答案

example fiddle

您想要在页面上创建一个隐藏元素,该元素将缓存或容纳您不希望看到的选项。然后,您将向该元素添加一些CSS,并使用jQuery在其中放置选项。


  的HTML


<select id="cd-dropdown" name="cd-dropdown" class="cd-select">
    <option value="-1" selected>Funds in your portfolio (3)</option>
    <option value="1">fund1 £60,000</option>
    <option value="2">fund 2 £40,000</option>
    <option value="3">fund 3 £24,000</option>
    <option value="4">View all funds &gt;</option>
    <option value="5">Fund 5 £40,000</option>
</select>

<input type="button" value="View all" class='view_more_button' />
<input type="button" value="View less" class='view_less_button hide' />



  的CSS


.hide {
    left: -9999px !important;
    position: absolute !important;
    visibility: hidden;
    z-index: -500;
    top: -9999px;
}



  的JavaScript


//Create on DOM element dynamically that will house options greater than three.
var blank_input = $('<select>', {
    class: 'hidden_input_field hide',
    name: 'hidden_fields'
});

//This variable caches the master select element.
var master_select_menu = jQuery('#cd-dropdown');

//Put the blank select field in the DOM tree to be select via jQuery selectors.
blank_input.appendTo(jQuery('body'));

jQuery('.view_more_button').on('click', function(e) {
    var place_holder_select_field = jQuery('.hidden_input_field');
    if (place_holder_select_field.children('option').length) {
        jQuery('.moved').each(function(index,element) {
            jQuery(element).appendTo(master_select_menu);
        });
        jQuery(e.target).addClass('hide');
        jQuery('.view_less_button').removeClass('hide');
    }
    master_select_menu.val(-1).change();
});

jQuery('.view_less_button').on('click', function(e) {
    view_three();
    jQuery(e.target).addClass('hide');
    jQuery('.view_more_button').removeClass('hide');
    master_select_menu.val(-1).change();
});

view_three();

//This function gets called as soon as the page loads, where it appends any option element greater than 3 to the hidden select field.
function view_three() {
    jQuery('option').each(function(index, element) {
        var place_holder_select_field = jQuery('.hidden_input_field');
        if (index > 3) {
            jQuery(element).addClass('moved').appendTo(place_holder_select_field);
        }
    });
}




//Create on DOM element dynamically that will house options greater than three.
var blank_input = $('<select>', {
    class: 'hidden_input_field hide',
    name: 'hidden_fields'
});

//This variable caches the master select element.
var master_select_menu = jQuery('#cd-dropdown');

//Put the blank select field in the DOM tree to be select via jQuery selectors.
blank_input.appendTo(jQuery('body'));

jQuery('.view_more_button').on('click', function(e) {
	var place_holder_select_field = jQuery('.hidden_input_field');
	if (place_holder_select_field.children('option').length) {
		jQuery('.moved').each(function(index,element) {
			jQuery(element).appendTo(master_select_menu);
		});
		jQuery(e.target).addClass('hide');
		jQuery('.view_less_button').removeClass('hide');
	}
	master_select_menu.val(-1).change();
});

jQuery('.view_less_button').on('click', function(e) {
	view_three();
	jQuery(e.target).addClass('hide');
	jQuery('.view_more_button').removeClass('hide');
	master_select_menu.val(-1).change();
});

view_three();

//This function gets called as soon as the page loads, where it appends any option element greater than 3 to the hidden select field.
function view_three() {
	jQuery('option').each(function(index, element) {
		var place_holder_select_field = jQuery('.hidden_input_field');
		if (index > 3) {
			jQuery(element).addClass('moved').appendTo(place_holder_select_field);
		}
	});
}

.hide {
    left: -9999px !important;
    position: absolute !important;
    visibility: hidden;
    z-index: -500;
    top: -9999px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="cd-dropdown" name="cd-dropdown" class="cd-select">
    <option value="-1" selected>Funds in your portfolio (3)</option>
    <option value="1">fund1 £60,000</option>
    <option value="2">fund 2 £40,000</option>
    <option value="3">fund 3 £24,000</option>
    <option value="4">View all funds &gt;</option>
    <option value="5">Fund 5 £40,000</option>
</select>

<input type="button" value="View all" class='view_more_button' />
<input type="button" value="View less" class='view_less_button hide' />

10-05 18:37