2013-04-25 2 views
1

В основном, что я делаю, вы делаете «вид больше». У меня есть небольшой абзац текста, описывающий что-то, над чем я работал, и кнопку в конце абзаца. I (Это действительно ссылка, с стилем кнопки). Когда кнопка нажата, div расширяется до 400 пикселей, а дополнительный текст добавляется с помощью .html(); но когда я нажимаю кнопку «Показать меньше», чтобы свернуть обратно к меньшему абзацу и 200px div, ничего не происходит.Изменение размера окна JQuery с помощью кнопки

JQuery

$(document).ready(function(){ 
var $mottheight = $('#row-mott').height(); 

if ($mottheight == 300) { 
    $('#mott-btn-collapse').click(function(){ 
    $('#row-mott').animate({ 
     height:200 
    }, 300); 
    $('#mott').html('I\'ve worked on the Warren Mott High School website since September of 2011. I am one of four student webmasters that keep the website in the best condition possible. We cannot take credit for all the coding, though. This website is run by around 40 Web Design students. As Webmaster, my job is to fix, improve, and help those students learn as they go. <a href="#" id="mott-btn" class="btn btn-mini">Less info &raquo</a>'); 

}); 
} 
else if ($mottheight < 300){ 
    $('#mott-btn').click(function(){ 
    $('#row-mott').animate({ 
     height:300 
    }, 400); 
    $('#mott').html('I\'ve worked on the Warren Mott High School website since September of 2011. I am one of four student webmasters that keep the website in the best condition possible. We cannot take credit for all the coding, though. This website is run by around 40 Web Design students. As Webmaster, my job is to fix, improve, and help those students learn as they go. I\'ve worked on the Warren Mott High School website since September of 2011. I am one of four student webmasters that keep the website in the best condition possible. We cannot take credit for all the coding, though. This website is run by around 40 Web Design students. As Webmaster, my job is to fix, improve, and help those students learn as they go. I\'ve worked on the Warren Mott High School website since September of 2011. I am one of four student webmasters that keep the website in the best condition possible. We cannot take credit for all the coding, though. This website is run by around 40 Web Design students. As Webmaster, my job is to fix, improve, and help those students learn as they go. <a href="#" id="mott-btn-collapse" class="btn btn-mini">Less info &raquo</a>'); 
    }); 
} 
else { 
    return 0; 
} 
}); 
+0

Помните, что код выполнен во время загрузки. Когда страница загружает первый оператор if, то false, поэтому привязка клика никогда не загружается. –

ответ

4

Ваша функция очень неловко закодированы. Вам нужно зафиксировать высоту внутри функции, а не просто при загрузке страницы, и вы можете объединить все элементы кликов.

var $row_mott = $('#row-mott'), 
    $mott = $('#mott'); 

$('#mott-btn-collapse').click(function(){ 
    var $mottheight = $row_mott.height(); 

    if ($mottheight == 300) { 
     $row_mott.stop().animate({height:200}, 300); 
     $mott.html('I\'ve worked on the Warren Mott High School website since September of 2011. I am one of four student webmasters that keep the website in the best condition possible. We cannot take credit for all the coding, though. This website is run by around 40 Web Design students. As Webmaster, my job is to fix, improve, and help those students learn as they go. <a href="#" id="mott-btn" class="btn btn-mini">Less info &raquo</a>'); 
    } else if ($mottheight < 300){ 
     $row_mott.stop().animate({height:300}, 400); 
     $mott.html('I\'ve worked on the Warren Mott High School website since September of 2011. I am one of four student webmasters that keep the website in the best condition possible. We cannot take credit for all the coding, though. This website is run by around 40 Web Design students. As Webmaster, my job is to fix, improve, and help those students learn as they go. I\'ve worked on the Warren Mott High School website since September of 2011. I am one of four student webmasters that keep the website in the best condition possible. We cannot take credit for all the coding, though. This website is run by around 40 Web Design students. As Webmaster, my job is to fix, improve, and help those students learn as they go. I\'ve worked on the Warren Mott High School website since September of 2011. I am one of four student webmasters that keep the website in the best condition possible. We cannot take credit for all the coding, though. This website is run by around 40 Web Design students. As Webmaster, my job is to fix, improve, and help those students learn as they go. <a href="#" id="mott-btn-collapse" class="btn btn-mini">Less info &raquo</a>'); 
    } 
}); 

Примечание:

  • я преобразовал свои селекторы в переменные кэшируются; его хорошая практика при использовании селектора несколько раз
  • Я добавил .stop() до вашей анимации, чтобы предотвратить избыточную очередность
  • Я объединил действие в одну кнопку; это более личное предпочтение, но для более последовательного взаимодействия с пользователем, когда одна кнопка «Expand/Collapse» довольно стандартизирована
+0

Ударь меня снова! Хорошая работа! –

+0

Это то, что я пытался сделать в своем ответе, но я сделал его еще более неудобным, чем оригинал, поэтому я просто удалил его. Хорошая работа. +1 Buddy :) – War10ck

+0

Я сейчас вдалеке от своего компьютера, но когда я вернусь, я попробую это. Спасибо за помощь! – RonnieEXP

0

Вы работаете только с обработчиками щелчков. Таким образом, при загрузке документа он находит высоту # row-mott, устанавливает ее и оценивает то, что у вас есть. По умолчанию это < 300. Вам нужно проверить высоту внутри события клика, а не раньше.

0

попробовать это ..

$(document).ready(function(){ 
    var $mottheight = $('#row-mott').height(); 
    $('#mott-btn-collapse').click(function(){ 
     if ($mottheight == 300) { 
    $('#row-mott').animate({ 
      height:200 
     }, 300); 
     $('#mott').html('I\'ve worked on the W...</a>'); 

    }); 
    }else if($mottheight < 300){ 
     $('#mott-btn').click(function(){ 
     $('#row-mott').animate({ 
      height:300 
     }, 400); 
     $('#mott').html('I\'ve worked on the Warren Mott....they go. <a href="#" id="mott-btn-collapse" class="btn btn-mini">Less info &raquo</a>'); 
     }); 
    } 
    }); 
0

Я понял это. Это было очень просто, и я честно не знаю, почему я об этом не думал раньше.

$(document).ready(function(){ 

    $('#mott-appended').hide(); 
    $('#patrick-appended').hide(); 

    /* Start Warren Mott High School text show/hide */ 

    $('#mott-btn').click(function(){ 
    $('#mott-appended').show('slow'); 
    $(this).hide('slow'); 
    }); 

    $('#mott-btn-collapse').click(function(){ 
    $('#mott-appended').hide('slow'); 
    $('#mott-btn').show('slow'); 
    }); 

    /* End Warren Mott High School text show/hide */ 
    /* Start Patrick Studios text show/hide */ 

    $('#patrick-btn').click(function(){ 
     $('#patrick-appended').show('slow'); 
     $(this).hide('slow'); 
    }); 

    $('#patrick-btn-collapse').click(function(){ 
     $('#patrick-appended').hide('slow'); 
     $('#patrick-btn').show('slow'); 
    }); 

    /* End Patrick Studios text show/hide */ 

}); 
Смежные вопросы