2012-11-20 59 views
0

我想更改附加事件的元素。在下面的例子中,我尝试将border从2px增加到10px,但没有成功。发生事件时更改元素

完整的小例子(查找失败行):

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
    <head> 
    <title>Example</title> 
    <style>P { margin-bottom: 40%; }</style> 
    </head> 
    <body> 
    <p>Paragraph 1</p> 
    <p>Paragraph 2</p> 
    <p>Paragraph 3</p> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
    <script> 

$('p').each(function (i) { 
    $(this).css('border', '2px solid'); 

    $(window).scroll(function (event) { 
     console.log('scroll triggered, but nothing happens!'); 
     event.target.css('border', '10px solid'); // FAILS with TypeError: event.target.css is not a function 
    }); 
}) 

    </script> 
    </body> 
</html> 
+0

正是你试图改变边界是什么?整个窗户? –

+0

@ShadowWizard:来自'2px'的每个''p'我最初在发生滚动时使用jQuery设置为'10px'。编辑:我看到我的错误 – Deleted

回答

1

您将event.target是窗口本身,所以你不能应用CSS到p标签这种方式,虽然可以做到这一点的方法:http://jsbin.com/abebof/1/edit

$('p',event.target).css('border', '10px solid'); 
1

明确地选择您想要的CSS应用到元素(一个或多个)。

$(window).scroll(function (event) { 
     console.log('scroll triggered, but nothing happens!'); 
     $('body').css('border', '10px solid'); // FAILS with TypeError: event.target.css is not a function 
    }); 

即使你使用event.target,你将不得不把它包在一个jQuery集合之前,你可以使用.css方法:

$(event.target).css... 

的问题,这是在应用CSS到窗口没有按不工作;您只能将css应用于HTMLElement对象(可从文档中找到)。

相关问题