php - 更改子菜单时如何更改网页背景?

原文 标签 php css html

How to change the background of the webpage, when changing sub-menu?

I'm teaching myself php/html/css and am stuck on how to change the background of a page for each subpage.

Example:

  • when in main page, if I press in "header > contacts" the background would change to a new image.

I tried in css but it doesn't change the whole page image, since what I'm changing is in <section> part.

Webpage of training (http://kamiexp.co.nf)

Answer

You need Javascript to achieve that. Given the following html.

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="script.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <header>
    some content
  </header>
  <button id="toggleColor">click</button>
</body>
</html>

Simply create another file in the same directory called script.js and add this code.

(function($){

  var $toggle = $('#toggleColor');
  var $header = $('header');

  $toggle.click(function(){

    $header.css('background', 'red');

  });
})(jQuery);

when the button with id toggleColor is clicked, header element will change color. To learn how Jquery works I'd recommend you started here Jquery tutorial

You may also want to toggleClass. To do this just create a css rule like this one .red{background:red;} then simply do $header.toggleClass('red'). I've updated the Demo link.

Demo

翻译

我正在自学php / html / css,并且坚持如何更改每个子页面的页面背景。

例:


在主页上时,如果按“标题>联系人”,则背景将更改为新图像。


我在CSS中尝试过,但它不会更改整个页面图像,因为我要更改的内容在<section>部分中。

培训网页(http://kamiexp.co.nf)
最佳答案
您需要使用Javascript来实现。鉴于以下html。

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="script.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <header>
    some content
  </header>
  <button id="toggleColor">click</button>
</body>
</html>


只需在同一目录中创建另一个名为script.js的文件,然后添加此代码。

(function($){

  var $toggle = $('#toggleColor');
  var $header = $('header');

  $toggle.click(function(){

    $header.css('background', 'red');

  });
})(jQuery);


单击ID为toggleColor的按钮时,header元素将更改颜色。要了解Jquery的工作原理,建议您从Jquery tutorial开始

您可能还想toggleClass。为此,只需创建一个.red{background:red;}这样的css规则,然后简单地执行$header.toggleClass('red')。我已经更新了演示链接。

Demo
相关推荐

php - Symfony2:如何避免数据库中已经存在重复的实体?

php - Eclipse中的PHP 7调试器设置

javascript - 访问URL参数-PHP和Angular.js

php - 使用更新的MySQL库修复PHP数据库连接失败

php - PHP代码不允许多个输入值通过我的表单发送

php - Laravel 5.1内部联接查询中的问题

php - 控制PHP ldap分页-结果数和页码

php - 带有PHPStorm 10的PHP7

php - 如何防止第二个正则表达式重新替换?

php - 如何在PHP的$ _SESSION中保存值并进行检索