将内联硬编码jQuery函数转换为变量

时间:2013-09-25 14:35:00

标签: javascript jquery html css variables

我有以下代码:

      <!-- work item 1 -->
      <li id="portfolio-1" class="col-12  col-sm-6  col-md-6  col-lg-4">
        <figure class="box  box--sm  text-center">
            <h4 class="brand--font-standard">Project Title</h4>
              <div class="row">
              <div class="col-xs-offset-2  col-xs-8  col-sm-offset-1  col-sm-10  col-md-offset-2  col-md-8  col-lg-offset-3  col-lg-6">
                  <img src="img/globe.jpg" class="img-responsive" alt="globe">
                </div>
              </div>
            <figcaption>
              <p>Project comment</p>
              <a href="#" class="pull-right  brand--font" onclick="$('.work--detail').addClass('work--detail_show'); $('#work-2, #work-3, #work-4, #work-5, #work-6').hide(); $('#work-1').slideDown(); $('html, body').animate({scrollTop: $('.hidden-content-top').offset().top - 110 }, 1000); return false;">View</a>
            </figcaption>
        </figure>
      </li><!-- /work item 1 -->

我想重写锚标记上的js,以便它不是硬编码的,而是为需要打开/添加.hide的项添加变量。目前有6个li的ID为#portfolio-(数字),每个都有相应的隐藏内容,ID为#work-(数字)。

我想要这样做的原因首先是整理代码并使其更加可重用。但是,由于网站响应,我需要根据窗口宽度调整偏移值。

相应的隐藏内容也需要从变量开始,而不是硬编码。一个例子是:

<a href="#" class="btn  btn--small  btn--grey  brand--font" onclick="$('#work-1').slideUp(); $('html, body').animate({scrollTop: $('#portfolio-1').offset().top - 140 }, 1000); $('.work--detail').removeClass('work--detail_show'); return false;">close</a>

我目前有以下功能(获取窗口宽度):

var _getInnerWidth = function () {
return typeof window.innerWidth !== 'undefined' ? window.innerWidth : document.documentElement.clientWidth;

感谢任何帮助!

Demo is here

PS - 我可以处理第二部分(根据窗口宽度添加偏移值等)

PPS - 我是js的新手,所以请保持温柔:)

1 个答案:

答案 0 :(得分:1)

如果我是你,我会在代码中添加一些清晰度:

var _getInnerWidth = function () {

    if(typeof window.innerWidth !== 'undefined'){
      innerWidth = window.innerWidth;
    } else {
      innerWidth = document.documentElement.clientWidth;
    }

    return innerWidth;
}

您的代码应该按原样运行。我试过了,然后回到了我的身边1704。

我在这里附上了一个plunker,其中有一些我根据你正在做的事情描述建立的东西的例子。希望它有所帮助

http://plnkr.co/edit/KXNGL089UIvfNlRmO2cC

相关问题