我创建了yii 1应用程序,并使用以下脚本在视图文件中导航:
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});但是,当我创建yii2应用程序并粘贴此代码时,它无法工作。然后,我创建了新的menu_navigate.js js文件并粘贴了如下代码
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});我使用以下代码在ThemeAsset中注册了此代码:
public $js = [
'Index/menu_navigate.js'
]但是,这段代码对我没有帮助,也不能正常工作。我找不到任何错误。在控制台屏幕上显示以下错误消息
GET http://all/themes/CompanyProfile/Index/menu_navigate.js(未找到)
发布于 2016-09-14 12:53:41
使用“/Index/menu_Navigate.js”,这将帮助您获得正确的路径。
发布于 2016-09-14 13:40:02
如果此文件位于web可访问目录之外,则需要在资源包中设置正确的sourcePath:
<?php
namespace app\assets;
use yii\web\AssetBundle;
class MenuNavigationAsset extends AssetBundle
{
public $sourcePath = '@bower/font-awesome'; // Replace with folder where "Index" folder is located. Path should be absolute, you can use aliases here.
public $js = [
'Index/menu_navigate.js',
];
}然后,它将被复制到web可访问目录,并从那里加载。您可以通过官方文档来定义别名here。它可以防止你硬编码绝对路径。
否则(如果文件位于web可访问的目录中),请设置basePath和baseUrl属性:
<?php
namespace app\assets;
use yii\web\AssetBundle;
class MenuNavigationAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $js = [
'Index/menu_navigation.js',
];
}准确检查浏览器尝试加载此js文件的路径,如果路径正确,则确保该文件存在;否则,请确保资源束中的路径正确。
还要检查path是否有拼写错误。
有关使用资产的官方文档,请参阅here。
https://stackoverflow.com/questions/39482660
复制相似问题